ES6 JavaScript Environment Setup for ASP.NET MVC 5 – Using Webpack 4 & Babel

In this Article shows you how to setup ASP.NET MVC 5 project to enable ES6 JavaScript environment using Webpack 4 and Babel.

What is Webpack?
From the Webpack 4 official website (https://webpack.js.org):
“Webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles. Since version 4, webpack does not require a configuration file to bundle your project. Nevertheless, it is incredibly configurable to fit your needs better.”

  • Webpack is a module blunder, but you can also use it for running tasks as well.
  • Webpack relies on a dependency graph underneath. Webpack traverse through the source to construct the graph and it uses this information to construct the final bundles.
  • Webpack relies on loaders and plugins. Loaders operate on a module level, while plugins rely on hooks provided by webpack and have the best access to its execution process.
  • Webpack can generate hashes for filenames allowing you to invalidate past bundles as their content change.

Why would I use a Webpack?

Webpack’s execution process:

What is babel?
Babel is a great way to use cutting-edge JavaScript features on older implementations. The word transpile means Babel rewrites JavaScript code into other JavaScript code, specifically to rewrite JavaScript code into JavaScript code, applying desired transformations such as converting ES2015/2016 features into ES5 code that can run in a web browser.

Step1: Create ASP.NET MVC 5 empty web application project
File => New => Project
Choose the “Empty” template option and select MVC checkbox and click OK.

Step 2: Set up NPM configuration
Option 1:
Open command prompt and go to the root project and type below command
npm init -y

Note: “-y” option creates a new file without prompting the user.
after successfully ran the command , npm creates package.json file under the root folder, you need to explicitly include this file in to visual studio, click on “show all files”


Right click the package.json file and include in project

Option 2: you need to create package.json file in the root folder and then open the command prompt pointing to the root folder and type below command
npm init -y
above command will update the package.json with default configuration entry’s.

Step 3: Install Webpack 4 and Babel
First install the following Webpack packages: go to the rood directory of your project and type below command
npm install –save-dev webpack webpack-cli

This will update the package.json file

Before adding any ES6 features to our demo asp.net mvc application , we should test the webpack build works or not.
1. Open package.josn and add a new build script.

“name”: “EnableES6InAspnetMvc5Demo”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“build”: “webpack”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“devDependencies”: {
“@babel/core”: “^7.2.2”,
“@babel/preset-env”: “^7.3.1”,
“babel-loader”: “^8.0.5”,
“webpack”: “^4.29.3”,
“webpack-cli”: “^3.2.3”
}
File: package.json

2. Go to command window and point to your root directory, run the build script in your terminal
npm run build
3. You will see this error

The error you get in the terminal will look this: ERROR in Entry module not found: Error: Can’t resolve ‘./src’ in C:\WorkinProgress\projects\EnableES6InAspnetMvc5Demo\EnableES6InAspnetMvc5Demo’

4. Because we’re now in Webpack 4, by default , the main entry point is src/index.js , Let’s create this file to be able to build our first module

console.log(‘Index file…’);

File: src/index.js
5. If you re-run the build script, you will see that Webpack creates a new bundle file called main.js in the dist folder (again, this is by default)

The warning let us know that we can choose the mode between production or development.
Set mode to development or production to enable defaults for each environment. Lear more at https://webpack.js.org/concepts/mode/
Default is production mode


You will see dist/main.js file, default minified because of production mode
Webpack 4 has two modes: production and development, in Webpack 3 , you need to create a config file for each one, now you can get the same result just with a single line. Lets add a script to get our application to start using development mode
{
“name”: “EnableES6InAspnetMvc5Demo”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“build-development”: “webpack –mode development”,
“build”: “webpack –mode production”

},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“devDependencies”: {
“@babel/core”: “^7.2.2”,
“@babel/preset-env”: “^7.3.1”,
“babel-loader”: “^8.0.5”,
“webpack”: “^4.29.3”,
“webpack-cli”: “^3.2.3”
}
}

Now run the below command in Terminal
npm run build-development

File: dist/main.js

Now type below command in Terminal
npm run build

File: dist/main.js

————————————————– Visual Studio + ES6 ——–
Now webpack build working in both development / production. Below are the steps to add ES6 features and build the same using Webpack 4 and Babel to transform ES6 in to ES5 browser compatible

Let’s create some JavaScript files to transpile for a testing. Under project root, create a folder “Scripts” if one doesn’t exist. Create two more folders, “build” and “es6” under “Scripts”.


Create a file called Scripts/es6/numbers.js and import it to our Scripts/es6/index.js to test our babel-loader
export const numbers = ['one', 'two', 'three', 'four'];
File: Scripts/es6/numbers.js

import { numbers } from './numbers';
numbers.forEach(number => console.log(number));

File: Scripts/es6/index.js

6. Create an ASP.NET Controller and a View
Right click on “Controller” folder and create an empty controller names, “HomeController”

Right click on Index action method and click on add view menu
Add the bundled script reference in _Layout.cshtml file

If you want to implement Babel with Webpack 4 to transpile ES6 code, you need to use babel-loader, and you may need to install the following packages.
NOTE: The recent Babel upgrade to version 7 changed the namings of the node packages.
npm install –save-dev @babel/core babel-loader @babel/preset-env
If you open package.json, you can see that “devDependencies” section has references to babel and webpack

8 Create .babelrc file at the root of your project and then add this code:
{
“presets”: [ “@babel/preset-env” ]
}
File: .babelrc
Add out babel-loader using a webpack.config.js file at the root of your project and add this code:
const path = require(‘path’);

module.exports = {
entry: ‘./Scripts/es6/index.js’,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [‘babel-loader’]
}
]
},
output: {
path: path.resolve( __dirname, ‘./Scripts/build’),
publicPath: ‘/’,
filename: ‘bundle.js’
}

};
Once both webpack and babel set, open the terminal window and point to the root directory type:
npm run build
or
npm run build-development

Go back to Visual studio, include the bundle.js file:

Now go back to _Layout.cshtml and change the script reference as below

File: /Views/Shared/_Layout.cshtml

Now Run the application and open chrome development tools , you will see the numbers array

If you are using Visual studio 2017, we can automate the npm build in two ways:
Option 1:
Visual Studio has extension to run the npm commands using Task Runner extension, here is the Url
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner

once extension has been installed, open visual studio and right click on “package.json” file , you will see a new menu item called “Task Runner Explorer”.

Click on “Task runner Explorer” , you will see two options (build/ build- development) select one and run

Option 2:
We can configure Visual Studio to run “npm run build” or “npm run build-development” using Build Events, here are the steps

Right click the project => properties, go to Build Events
In the Pre-build event command line, enter below code snippet to run the webpack build when you compile the project.
npm run build –prefix$(ProjectDir)
or
npm run build-development –prefix$(ProjectDir)
once done save the file, build the project, if everything works , you will see the below output.

Full source code for this demo is available on Github

-Thank you

local_offerevent_note February 12, 2019

account_box srinivasaraju nadimpalli


local_offer