Setup webpack in asp.net mvc project

Let's create a dot net mvc core project, ProjectDotNetMvc


  1. Create a folder, for example ProjectDotNetMvc, ie. mkdir ProjectDotNetMvc
  2. Go inside a folder. ie. cd ProjectDotNetMvc
  3. Create dot net mvc project using command. ie. dotnet new mvc ; Note: here prerequisitues is you have dotnet core installed. https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-vsc?view=aspnetcore-2.0 
  4. Open project in visual studio code. Type command code .
  5. Type dotnet restore to install all dependencies.
  6. Finally run dotnet run to start your web app. check localhost for browsing site. https://localhost:5001/ 
  7. Now setup webpack in the project. Type npm init for initializing the npm in project. => this will create a package.json file in project.
  8. Let's install file required to transpile the ES6 javascript files. => npm install webpack babel-core babel-loader babel-polyfill babel-preset-es2015 => Learn about babel: https://babeljs.io/
  9. Now lets add the webpack configuration file to project. In the root project folder create a new file called, webpack.config.js and include the following code on it. 
const path = require('path');

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

    10. Now lets create some es6 class
export default class Project{
constructor(name, duration){
this.name = name;
this.duration = duration;
}
detail(){
console.log("This ${this.name} project will complete in ${this.duration}");
}
}

   11. Now lets create a entry file, main.js
import Project from './Project';

var project = new Project("Aspnet Mvc with webpack", "4 months");
project.detail();

  12. From our webpack configuration, bundled file will be stored on Script/build/bundle.js file. So, lets include that script in Views/Shared/_Layout.cshtml file.
.
.
.
</environment>
@RenderSection("Scripts", required: false)
<script src="~/Scripts/build/bundle.js"></script>
</body>
</html>

13. Now lets change the package json script to load webpack when typed command npm run build.
{
"name": "projectdotnetmvc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build" : "webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^4.10.0"
}
}

14. Now type command, npm run build
Reference :

Comments