How to Use webpack to build a single-page vue. js Application

Source: Internet
Author: User
Use webpack to build vue. js single-page applications are currently under development. To achieve frontend and backend separate development, we decided to use the vue just released. js 2.0 and koa 2.0 are developed, and webpack is used in depth as a front-end packaging tool. We plan to enhance our understanding of webpack through exercises for better understanding. Next, I will perform in-depth exercises on development-related technologies and write a series of articles.


The required dependencies are as follows:

"dependencies": {    "babel-core": "^6.18.2",    "babel-preset-es2015": "^6.18.0",    "config": "^1.24.0",    "element-ui": "^1.0.0",    "es6-promise": "^4.0.5",    "vue": "^2.0.5",    "vue-router": "^2.0.1"  },  "devDependencies": {    "babel-cli": "^6.18.0",    "babel-loader": "^6.2.7",    "vue-loader": "^9.8.1",    "style-loader": "^0.13.1",    "extract-text-webpack-plugin": "^1.0.1",    "gulp": "^3.9.1",    "webpack": "^1.13.3",  },

In addition, it is best to use global installation for gulp-cli, webpack, and babel-cli, and npm install-g webpack to conveniently use commands on the command line. In addition, the installation and download speed of npm is also a matter of criticism. To speed up the installation of dependency packages, you can install cnpm or yarn. Currently, cnpm is used by myself.

2. webpack configuration file

After installing the dependency package, you can directly use the webpack command to package the package and use the webpacke. config. js configuration file to instruct webpack to be constructed according to the rules.

var webpack = require('webpack');var path = require('path');module.exports = {    entry: "./client/main.js",    resolve: {        extensions: ['', '.js', '.vue', '.scss','.css'],    },    output: {        path: path.join(__dirname, "./build/assets/"),        filename: '[name].[chunkhash:8].js',        chunkFilename: '[id].js',        publicPath: '/assets/',    },    module: {        loaders: [            { test: /\.vue$/, loader: 'vue'},            {                test: /\.js$/,                exclude: /node_modules|vue\/dist|vue-router\/|vue-loader\/|vue-hot-reload-API\//,                loader: 'babel'            }        ]    },    plugins:[        new webpack.optimize.CommonsChunkPlugin({            names: ['bundle']        }),    ]};


Note:

Entry: entry point. webpack builds the project from the js file set at the entry point. During the process, all entry points use the packages that are imported or require dependent, will be packaged into the files and paths specified in the output;

Output: Set the output path of the packaged file and the file name;

Module: Mainly loaders, loaders is the parser for webpack packaging, css, vue, babel, and scss all need to use npm to install the corresponding loader, only webpack can parse and process files in this format;

Plugins: it is a packaging plug-in for some webpacks. It has nothing to do with the parsing language. It is used to assist in construction and provides a wide range of additional functions.

3. parse the file

In the process of parsing Dependencies from the entry, webpack supports css, sass, and various external font files used. webpack itself does not have the processing capability of all built-in formats, by installing and configuring different loader implementations, we can introduce the corresponding loader according to the actual needs of the project, so that webpack can parse and package different applications.

Compiling es6 code into es5 is also implemented by installing babel-loader. to parse the syntax that vue. js puts template/script/style in a file, vue-loader is also required.

Webpack can be capable of parsing scss files by using style-loader, css-loader, and sass-loader. As shown in the following example, the loader syntax can be written in multiple ways:

loaders: [    { test: /\.vue$/, loader: 'vue'},    {        test: /\.css$/,        loader: "style!css"    },    {        test: /\.scss$/,        loaders: ["style", "css", "sass"]    },    {        test: /\.js$/,        exclude: /node_modules|vue\/dist|vue-router\/|vue-loader\/|vue-hot-reload-api\//,        loader: 'babel'    },    {        test   : /\.(ttf|eot|svg|svg|woff|woff(2))(\?t\=[0-9]+)?$/,        loader : 'file'    }]

4. Custom packaging rules

Based on the actual project requirements, you can use some webpack plug-ins to implement powerful functions without using gulp or grunt.

4.1 generate a hash fingerprint

To incrementally update the front-end static resources, use the built-in functions of webpack to generate a hash fingerprint for the bundle file. By setting the generated file name rules in the output, you can generate a bundle file with a hash fingerprint. Example:

output:{  ...  //filename: '[name].[hash:8].js',  filename: '[name].[chunkhash:8].js',  //filename: '[name].[contenthash:8].js',  ...}

Webpack provides three generation rules: hash, chunkhash, and contenthash. 8 in [hash: 8] is the number of hash digits.

Hash: Calculate the hash value based on the compilation process corresponding to the resource during compilation.

Chunkhash: Calculate the hash value based on the module content

Contenthash: Calculate the hash value based on the file content

4.2 package an independent js dependency package into a vendor

If jquery, bootstrap, fetch, or other js files that do not support require are used in the project, you can use webpack to package these files into a separate vendor file, optimize static file deployment and loading.

This operation is implemented through configuration in the entry. The CommonsChunkPlugin plug-in is used as a package for different modules. The configuration is as follows:

...

Entry :{

Bundle: ['./client/main. js'],

// The rule is consistent with that referenced by require.

Vendor: ['whatwg-fetch', 'jquery ']

},

...

Plugins :[

New webpack. optimize. CommonsChunkPlugin ({

Names: ['bundle', 'bad']

}),

]

...


4.3 package styles into independent css files

We can also use the ExtractTextPlugin plug-in to package the referenced style into a separate css or other style file. We can also generate a hash fingerprint.

...module: {    loaders: [        ...        {            test: /\.css$/,            loader: ExtractTextPlugin.extract("style-loader", "css-loader")        },        {            test: /\.scss$/,            loaders: ExtractTextPlugin.extract("style-loader", "css-loader","sass-loader")        }        ...    ]},...plugins:[    new ExtractTextPlugin("[name].[contenthash:8].css", {        allChunks: true    }),]...

4.4 introduce the bundle file with hash fingerprint into the html file

Finally, we need a function similar to the gulp-rev function to automatically introduce bundle and vendor files packed and compiled with hash fingerprints in html files. This process can be automatically completed by webpack, the HtmlWebpackPlugin plug-in is used. To compress the js file, you can use the UglifyJsPlugin plug-in. The plug-in configuration is as follows:

plugins:[    ...    new HtmlWebpackPlugin({        title: 'My App',        template: 'index.html',        filename: '../index.html'    }),    new webpack.optimize.UglifyJsPlugin({        compress: {            warnings: false        }    }),]

5. Use with gulp

In addition to using the previous gulp-webpack plug-in, you can also directly use the require ('webpackage') method in gulp to use webpack together with gulp. Simple configuration

webpack(require("./webpack.config.js"), function(err, stats) {    if(err) throw new gutil.PluginError("webpack:build", err);    gutil.log("[webpack:build]", stats.toString({        colors: true    }));    callback();});

6 source code

Finally, the source code of the entire project is on github. Other articles will be updated with the project at the same time later.

// Use gulp to call webpack packaging. The packaged code is run npm run build in the build directory. // run the static server with watch auto refresh that triggers webpack compilation. // http: // localhost: 3333npm run dev

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.