.NET MVC, Webpack and Vue.js — Part 4— Webpack Configuration
- Part 1 — Tools;
- Part 2 — Project structure;
- Part 3 — NPM Packages;
- Part 4 — Webpack Configuration;
- Part 5 — Vue.js;
- Part 6 — Vuex;
Now, we need to write the webpack.config.js to make the build of front-end files;
I plan to build one script per page, so each <view>.cshtml (if needed) will contains a .js file. That way I can use the two worlds: Razor for manipulating any ViewModel.cs data, check permissions to show/hide elements, doing all server check code and Vue.js to making more dynamic things and ajax requests. I did’nt plan to make request here, but in my working project, I used the mvc controllers as rest apis, making just get and posts requests.
This example could be not complete and you can feel free to say what can be better.
In the project root, create a webpack.config.js and open it. I’ll try to explain each part of the config file.
First, we need to load the tools;
I created two const that will have the source path of our js code and an object that will contains our entries for webpack:
Now, we have to create all entries for the application. How we’ve a js code for each view, we will create a sub-directory in the ~/public/src/js, named with the view name and a index.js file, that way, webpack will uses these index.js file as entry and import all the modules that each file has to need to import.
Now, we exports the webpack configuration:
In the package.json, on the scripts, remove the test script and add:
“build”: “webpack”
Save the file, open a CMD/PowerShell at root of the project and run
npm run build
Now, we have in the public directory, a dist directory (hided by Visual Studio). Include in the project and put the references of these files in the _Layout.cshtml:
Be atention that the @RenderSection(“scripts”, false), we will use this to put our code in another pages after the main code;
Starting the debug and voilá, we our application runing with css and js code.
Next post, I’ll show how I wrote my Vue code and another resource that I have found for keep the Vue state after page reloading.
See ya.