Setup Webpack and Vue 2.
Up and running with webpack and vue.
Since you are reading this I assume you want to see some code so I’ll skip the part of What is this Webpack thing and why use it. Lets get to it shall we.
Get yourself a clean project directory (its a good idea to setup version control) and setup a structure as shown below, this might change as you start adding routing and store components but for now this will do.
npm init in the directory to setup the
package.json file. Follow the wizard when finished you should have a file that looks like the one below.
Create a file titled
webpack.config.js in the root of your project directory. This wil specify the webpack configuration (obviously) .
I won’t go over all the options in the config sinds most are obviously.
The configuration file will act different based on the
env variable when the var is set for production the app will be uglified and will define a global constant that will be compiled at runtime by wepback, the vue package wil use this constant internally to disable the developer tools.
Further we have a babel loader translating our fancy es6 code to an older version so it can be interpreted by older browser engines, and the
vue-loader to validate vue files on compile note that this is just a syntax check it won’t test other stuff so its best practice to write tests.
Depending on how you structure your vue components you will have to resolve the vue instance for a stand alone build. If, like me you provide your template code as a string instead of a render function or need to use in DOM templates you will need the stand alone build. It is however (30% slower), but hey who cares about speed :’). If you want to read more about it take a look over here.
Lets add the packages. I prefer
yarn to manage my packages but you can use
npm if you prefer it.
yarn add webpack babel-core babel-loader babel-preset-es2015 css-loader uglifyjs-webpack-plugin --dev
Add the following commands to the scripts section in your
If all went well you can run the command
yarn dev or
yarn build and a js file should have been added in your
/build folder… YAAY.
The vue part.
Now that we can compile our app lets at some useful things to it. Add vue and its dev packages.
yarn add vue
yarn add vue-hot-reload-api vue-html-loader vue-loader vue-template-compiler --dev
html.index, it doesn’t have to contain more then the basic tags and an element to which our App instance can bind, the app instance can not be bound to the
html tag. Don’t forget to import your compiled app file.
Now for the
main.js file. Just import vue and create a new instance that binds to the previous defined element in the html file.
Thats all for this article :), now everything is in place to start building your vue app. (full application)