Integrating ES6 with .Net MVC in Microsoft Visual Studio 2017
Integrating ES6 with .Net MVC in Microsoft Visual Studio 2017 by Mustafa Salaheldin

Integrating ES6 with .Net MVC in Microsoft Visual Studio 2017

Since I started my development using the ES2015 standard for JavaScript and I was wondering how to integrate that with ASP.net MVC projects in Microsoft Visual Studio.

Of course you can use out of the box frameworks like Angular, VUE or React templates that come with VS to integrate such standard in your environment, but what I was looking for was something much simpler, I just need to write my code in ES6 and call it from the MVC views.

So in the following steps I will show how I did the integration and how to keep your code monitored so that when you make a change in your IDE, it updates your browser in debugging mode.

1. Set up ASP.NET MVC 5

Create a new solution in Visual Studio. I am using VS 2017 Professional, then create a new ASP.NET MVC 5 project. Right click on Solution and then “Add -> New Project” and select an “Web API” template.

No alt text provided for this image

2. Set up npm configuration and packages

Open any command line shell (Git bash or cmd for example) and navigate to the root of the project, then create a new “package.json” configuration file for npm by running following command.

> npm init -y

(“-y” option creates a new file without prompting the user.)

No alt text provided for this image

Note: Just make sure that the name section value is all in lower case.

3. Install Webpack and Babel

Run the following command in your command shell.

npm install --save-dev babel-core babel-loader babel-polyfill babel-preset-env @babel/cli @babel/core @babel/plugin-proposal-class-properties @babel/preset-env browser-sync browser-sync-webpack-plugin webpack webpack-cli webpack-notifier

The above command will install necessary packages for Babel and Webpack.

No alt text provided for this image

Now let’s include package.json in VS Solution Explorer.

Go to “Solution Explorer” and click on “Show All Files” button, “package.json” will show up in the explorer.

Right click on “package.json” and include it in the project.

No alt text provided for this image


4. Create some ES6 javascript files

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

Create two javascript files under “es6” folder.

1.   person.js: contains “Person” class.

2.   main.js: main entry point for the application.

No alt text provided for this image


The person.js should be like the following:

 export default class Person {

    constructor(name, age) {

        this.name = name;

        this.age = age;

    }

speak() {

        console.log(`Hi I'm ${this.name} and ${this.age} years old and I am awesome`);

    }

}

The main.js should be like the following:

import Person from './person'; 

var person = new Person("David", 20);

person.speak();

5. Emending ES6 transpiled files

Add a script tag in “Views/Shared/_Layout.cshtml”.

<script src="~/Scripts/build/bundle.js"></script>

No alt text provided for this image



And don't forget to include the bundle file in your project.

No alt text provided for this image

6. Configure Webpack

  • Create webpack.config.js on project root. Add following configuration option in the file.

"use strict";

const path = require('path');

var WebpackNotifierPlugin = require("webpack-notifier");

var BrowserSyncPlugin = require("browser-sync-webpack-plugin");

module.exports = {

   entry: ['./Scripts/es6/main.js'],

   output: {

       path: path.resolve(__dirname, './Scripts/build'),

       filename: 'bundle.js'

   },

   // IMPORTANT NOTE: If you are using Webpack 2 or above, replace "loaders" with "rules"

   module: {

       rules: [{

           test: /\.js$/,

           exclude: /node_modules/,

           use: {

               loader: "babel-loader"

           }

       }]

   },

   devtool: "inline-source-map",

   plugins: [new WebpackNotifierPlugin(), new BrowserSyncPlugin()]

};

* “entry” indicates files for webpack to work on.

* “output” specifies which folder (“path”) to write to while “filename” specifies what the result file name should be.

* “module” instructs webpack to use Babel to transpile.

* “test” tells webpack to include all files with “.js” extension while “exclude” leaves out “node_module” folder.

Now let’s update “package.json” to instruct npm to call webpack.

  • Add a “scripts” section.

 "scripts": {

   "dev": "webpack --mode development --watch",

   "build": "webpack --mode production"

 },

We can configure Visual Studio to run "npm run build" during compile time. Right-click on the project and select “properties” and go to “Build Events”. In the “Pre-build event command line:” enter following code snippet to run webpack when you compile the project.

 npm run build --prefix $(ProjectDir)

No alt text provided for this image
  • Configure Babel

Open “package.json” and add Babel Preset.

 "babel": {

   "presets": [

     "@babel/preset-env"

   ],

   "plugins": [

     "@babel/plugin-proposal-class-properties"

   ]

 },

Presets are basically a set of plugins so that you don’t have to specify every plugin that are needed by Babel one by one. I will use ES2015 preset, which includes all Babel plugins listed here. You can find a list of all Official Babel Presets in this link.

7. Run ASP.NET MVC

Run the project by pressing “F5”.

If you see “Hi I’m David and 20 years old and I am awesome”, then it’s set up properly.

No alt text provided for this image

8. Install Visual Studio Extensions (NPM Task Runner)

This is an optional step but to make our lives easier, let’s install a Visual Studio extension, NPM Task Runner for running npm scripts from Visual Studio.

No alt text provided for this image

9. Transpiling and Running

You could run the dev script within package.json file but let’s use the NPM task runner to make the life easier. Open the “Task Runner Explorer” by right clicking on package.json file in the project root.

No alt text provided for this image

Start dev script (double click), which monitors the changes in index.js.

No alt text provided for this image

To enable browser-sync, you need copy a script generated by browser-sync message in _Layout.cshtml under Shared folder near end of </body> tag.

No alt text provided for this image
No alt text provided for this image

If you are using browser-sync, you can clear the “Pre-build event command line” command added in step 6 (because browser-sync runs the build script, which calls webpack in turn).

10. Reloading Browser Automatically

You’ve installed browser-sync* packages so as you setup your code, the browser will reload automatically upon saving.

Finally I would like to give some credits to Sung M. Kim for Setting up an ES6 Environment for ASP.NET MVC 5 and Setting up a React Environment for ASP.NET MVC. I used those articles to create my hybrid version.

 

Nigel Salvador

Application Development Manager at Townsend Group Holdings, LLC

1 年

This sir was very, very, very helpful. Completely changed my ASP.NET MVC development environment. From the bottom of my heart, thank you!

回复
Troy Boettger

Software Engineer @ DMG

4 年

You literally copied his article word for word, added a babel plugin, and claimed you based yours off of his. You just rewrote it and put it on your Linkedin.

回复

要查看或添加评论,请登录

Mustafa Salaheldin的更多文章

社区洞察