Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundling and minification of ES6 javascript files in an asp.net MVC web application

We know that System.Web.optimization does not support ES6 javascript files bundling and minification, So how to support that?

like image 334
Simple Code Avatar asked Oct 01 '20 13:10

Simple Code


People also ask

What is minification and bundling in ASP NET MVC?

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)

Can we use bundling and minification with ASP NET web forms like MVC?

To optimize the performance of an application I found that bundling and minification can significantly improve the performance. It can be applied on MVC as well as in ASP.NET web forms.

What is bundling and minification in ASP.NET core?

What is bundling and minification. Bundling and minification are two distinct performance optimizations you can apply in a web app. Used together, bundling and minification improve performance by reducing the number of server requests and reducing the size of the requested static assets.

How can create JavaScript bundle in MVC?

How to create and use a ScriptBundle in ASP.NET MVC? JavaScript bundles can be created only in ~/App_Start/BundleConfig. cs page. To create a JavaScript bundle we use ScriptBundle class by passing virtual path as parameter in the constructor.


1 Answers

  1. Install BuildBundlerMinifier NuGet package to your project.
  2. Add a package.json file, with the following devDependencies, to the root of your project:

{
  "name": "YourProjectName",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "devDependencies": {
    "del": "^3.0.0",
    "gulp": "^4.0.0",
    "gulp-concat": "^2.6.1",
    "gulp-cssmin": "^0.2.0",
    "gulp-htmlmin": "^3.0.0",
    "gulp-terser": "^1.4.0",
    "gulp-uglify": "^3.0.0",
    "merge-stream": "^1.0.1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  1. Run the following npm commands inside your project root:

npm i

npm i -g gulp-cli

  1. Add the following gulpfile.js file below to the project root:

'use strict';

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-cssmin'),
    htmlmin = require('gulp-htmlmin'),
    uglify = require('gulp-uglify'),
    merge = require('merge-stream'),
    del = require('del'),
    bundleconfig = require('./bundleconfig.json');
const terser = require('gulp-terser');

const regex = {
    css: /\.css$/,
    html: /\.(html|htm)$/,
    js: /\.js$/
};

gulp.task('min:js', async function () {
    merge(getBundles(regex.js).map(bundle => {
        return gulp.src(bundle.inputFiles, { base: '.' })
            .pipe(concat(bundle.outputFileName))
            //.pipe(uglify())
            .pipe(terser())
            .pipe(gulp.dest('.'));
    }))
});

gulp.task('min:css', async function () {
    merge(getBundles(regex.css).map(bundle => {
        return gulp.src(bundle.inputFiles, { base: '.' })
            .pipe(concat(bundle.outputFileName))
            .pipe(cssmin())
            .pipe(gulp.dest('.'));
    }))
});

gulp.task('min:html', async function () {
    merge(getBundles(regex.html).map(bundle => {
        return gulp.src(bundle.inputFiles, { base: '.' })
            .pipe(concat(bundle.outputFileName))
            .pipe(htmlmin({ collapseWhitespace: true, minifyCSS: true, minifyJS: true }))
            .pipe(gulp.dest('.'));
    }))
});

gulp.task('min', gulp.series(['min:js', 'min:css', 'min:html']));

gulp.task('clean', () => {
    return del(bundleconfig.map(bundle => bundle.outputFileName));
});

gulp.task('watch', () => {
    getBundles(regex.js).forEach(
        bundle => gulp.watch(bundle.inputFiles, gulp.series(["min:js"])));

    getBundles(regex.css).forEach(
        bundle => gulp.watch(bundle.inputFiles, gulp.series(["min:css"])));

    getBundles(regex.html).forEach(
        bundle => gulp.watch(bundle.inputFiles, gulp.series(['min:html'])));
});

const getBundles = (regexPattern) => {
    return bundleconfig.filter(bundle => {
        return regexPattern.test(bundle.outputFileName);
    });
};

gulp.task('default', gulp.series("min"));
  1. Inside your .csproj file of your project add the following build task:

<Target Name="MyPreCompileTarget" BeforeTargets="Build">   
  <Exec Command="gulp min" />
 </Target>
  1. Add the following bundleconfig.json file below to the project root(here you can add js, css files need to be minified):

[
  {
    "outputFileName": "Content/css/site.min.css",
    "inputFiles": [
      "Content/css/site.css"
    ]
  },
  {
    "outputFileName": "Content/js/site.min.js",
    "inputFiles": [
      "Content/js/site.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "sourceMap": false
  }
]
  1. Inside your BundleConfig.cs you can do the following:

    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
      {
    
    
         bundles.Add(new Bundle("~/Content/css/site").Include(
                  "~/Content/css/site.css"));
    
    
         bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                     "~/Content/lib/jquery/jquery-{version}.js"));
    
         //use Bundle instead of ScriptBundle
         bundles.Add(new Bundle("~/Content/js/site").Include(
                     "~/Content/js/site.js"));
    
         //disable it for development environment
         if (Environment.Development)
         {
             BundleTable.EnableOptimizations = false;
         }
         else
         {
             BundleTable.EnableOptimizations = true;
         }
     }
    }
    
  2. Finally inside your view:

    @Styles.Render("~/Content/css/site")
    @Scripts.Render("~/Content/js/site")
    

My answer based on the following MSDN resources:

Bundling and Minification

Bundle and minify static assets in ASP.NET Core

like image 154
Simple Code Avatar answered Sep 20 '22 22:09

Simple Code