Detailed explanation of how to use webpack to build a front-end project, webwebpack

Source: Internet
Author: User
Tags macbook

Detailed explanation of how to use webpack to build a front-end project, webwebpack

I haven't written a technical blog for a long time. The reason is that I have recently learned the front-end technology. All of my colleagues know that I used Vue to build my resume and experience the latest front-end technology, however, we used the vue-cli scaffolding tool before. The most popular tools for front-end building are webpack and gulp. We talked about gulp in the previous article, in this article, we will discuss webpack.

Speaking of webpack, it is certain that the front-end users will not be unfamiliar. In fact, we used the webpack packaging technology when we used gulp for building. In fact, the relationship between gulp and webpack is not an alternative, they complement each other. Let's take a good look at the magic of webpack today.

We must first start with his official documents to learn a new technology. Of course, we should also learn the latest version. the official webpack tutorials are well written. You can read the official documents directly, the official documentation is definitely a better choice for you.

This article does not teach you how to read this article. It is enough to copy the Hydrology of official documents. Instead, it allows you to get started quickly and feel that the so-called webpack is actually the same thing, for webpack, you only need to remember a central idea and compress all the complicated file logic into several static resources like the figure above, let's look at the actual code.

Webpack. config. js

For some front-end developers who abandon jquery to welcome react and vue, although webpack may not have been written by themselves, it is always seen. Generally, there will bewebpack.config.jsThe following code is a simple webpack configuration file.

Var debug = process. env. NODE_ENV! = "Production"; // whether it is a test environment var webpack = require ('webpackage'); // import the webpack package var path = require ('path'); module. exports = {// fixed webpack export method context: path. join (_ dirname), devtool: debug? "Inline-sourcemap": null, // whether to use the map tool for the browser debug entry :". /src/js/root. js ", // packed entity module: {loaders: [// loaded configuration {test :/\. js? $/, Exclude:/(node_modules)/, loader: 'babel-loader ', query: {presets: ['react', 'es2015 '], // Add the Preprocessor plugins: ['react-html-attrs'], // Add the plug-in configuration of the component}, {test :/\. css $/, loader: 'style-loader! Css-loader '}, {test:/\. less $/, loader: "style! Css! Less "}]}, output: {// output path and file name path: _ dirname, filename:"./src/bundle. js "}, plugins: debug? []: [// Some plug-ins new webpack. optimize. dedupePlugin (), new webpack. optimize. occurenceOrderPlugin (), new webpack. optimize. uglifyJsPlugin ({mangle: false, sourcemap: false}),],};

Webpack mainly includesentry, module, output, pluginsFor more information, see the official documentation. If you do not want to copy the above Code.

Compared with gulp, webpack is more streamlined in packaging, which is also a popular reason, but it is indeed simple to look at the above files, but there is room for further improvement.

Package. json

I will not talk much about npm. Let's look at the file directly.

{"Name": "webpack", "version": "1.0.0", "description": "", "main": "index. js "," scripts ": {// command line tool" test ":" echo \ "Error: no test specified \" & exit 1 "," watch ": "webpack -- progress -- watch", "start": "webpack-dev-server -- open -- config webpack. dev. js "," build ":" webpack -- config webpack. prod. js "}," keywords ": []," author ":" "," license ":" ISC "," devDependencies ": {// development environment dependency "babel-loader": "^ 7.1.2", "clean-webpack-plugin": "^ 0.1.16", "css-loader ": "^ 0.28.7", "csv-loader": "^ 2.1.1", "file-loader": "^ 0.11.2", "html-webpack-plugin": "^ 2.30.1 ", "json-loader": "^ 0.5.7", "lodash": "^ 4.17.4", "style-loader": "^ 0.18.2", "uglifyjs-webpack-plugin ": "^ 0.4.6", "webpack": "^ 3.6.0", "webpack-dev-middleware": "^ 1.12.0", "webpack-dev-server": "^ 2.8.2 ", "webpack-merge": "^ 4.1.0", "xml-loader": "^ 1.2.1"}, "dependencies ": {// production environment dependency "babel-plugin-import": "^ 1.5.0", "babel-plugin-react-html-attrs": "^ 2.0.0", "babel-preset-es2015 ": "^ 6.24.1", "babel-preset-react": "^ 6.24.1", "babelify": "^ 7.3.0", "react": "^ 15.6.1 ", "react-dom": "^ 15.6.1", "react-mixin": "^ 4.0.0", "react-router": "^ 4.2.0 "}}

The command line tool npm run build is equivalent to executing webpack -- config webpack. prod. js, while npm start is equivalent to executing webpack-dev-server -- open -- config webpack. dev. js. easy to understand.

In project dependencies, many plug-ins and loaders are added to build a webpack. This package, webpack-merge, is worth noting in the tutorials in official documents, this package allows us to isolate the production environment from the development environment. How can we see it?

First, we need to divide the previous webpack. config. js into three files --- webpack. common. js, webpack. dev. js, webpack. prod. js.

Webpack. common. js

This is the common configuration of webpack, which is similar to the previous one. We have imported two plug-ins, one is to clear the plug-ins and the other is to create html plug-ins.

const path = require('path');const webpack = require('webpack');const CleanWebpackPlugin = require('clean-webpack-plugin');const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = { entry: './src/index.js', plugins: [  new CleanWebpackPlugin(['dist']),  new HtmlWebpackPlugin({title: 'webpack'}),  new webpack.HashedModuleIdsPlugin() ], output: {  filename: '[name].[chunkhash].js',  path: path.resolve(__dirname, 'dist') }, module: {  rules: [   {    test: /\.js?$/,    exclude: /(node_modules)/,    loader: 'babel-loader',    query: {     presets: [      'react', 'es2015'     ],     plugins: ['react-html-attrs']    }   },   {    test: /\.css$/,    use: ['style-loader', 'css-loader']   }, {    test: /\.(png|svg|jpg|gif)$/,    use: ['file-loader']   }, {    test: /\.(woff|woff2|eot|ttf|otf)$/,    use: ['file-loader']   }, {    test: /\.(csv|tsv)$/,    use: ['csv-loader']   }, {    test: /\.xml$/,    use: ['xml-loader']   }  ] }};

rulesIn the configuration, we configure some files that may be used to webpack,babel-loaderIf you want to talk about this, you can open another article, which is actually a js compatibility tool, so you can understand it.

Webpack. dev. js

The configuration of the webpack development environment is very simple, that is, using the webpack-merge tool mentioned earlier, just like git, The webpack is merged. common. in addition to js configuration, the inline-source-map tool that can be debugged is added, as well as hot-updated content indexes.

const merge = require('webpack-merge');const common = require('./webpack.common.js');module.exports = merge(common, { devtool: 'inline-source-map', devServer: {  contentBase: './dist' }});

Webpack. prod. js

In the production environment configuration of webpack, a new compression plug-in and environment configuration plug-in are added. The development tools here are different from those under development repayment. For details, see the official documentation.

const webpack = require('webpack');const merge = require('webpack-merge');const UglifyJSPlugin = require('uglifyjs-webpack-plugin');const common = require('./webpack.common.js');module.exports = merge(common, { devtool: 'source-map', plugins: [  new UglifyJSPlugin({sourceMap: true}),  new webpack.DefinePlugin({   'process.env': {    'NODE_ENV': JSON.stringify('production')   }  }) ]});

Terminal

In this way, the configuration is complete, and we enter it on the terminal to see the effect:

cd ../ && npm i 

First, go to the directory and install the node package.

Npm run build

MacBook-Pro-15:webpack zhushuangquan$ npm run build> webpack@1.0.0 build /Users/zhushuangquan/Documents/code/webpack> webpack --config webpack.prod.jsclean-webpack-plugin: /Users/zhushuangquan/Documents/code/webpack/dist has been removed.Hash: 85b65f54ef1436b295a5Version: webpack 3.6.0Time: 1148ms              Asset    Size Chunks       Chunk Names  main.014ac9aa420264da48eb.js 671 bytes    0 [emitted] mainmain.014ac9aa420264da48eb.js.map  6.47 kB    0 [emitted] main           index.html 197 bytes     [emitted] [lVK7] ./src/index.js 184 bytes {0} [built]Child html-webpack-plugin for "index.html":   1 asset  [3IRH] (webpack)/buildin/module.js 517 bytes {0} [built]  [DuR2] (webpack)/buildin/global.js 509 bytes {0} [built]    + 2 hidden modules

We can see the packaged files:

Main1_14ac9aa4201_da48eb. js

!function(e){function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var t={};n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n(n.s="lVK7")}({lVK7:function(e,n,t){"use strict";document.body.appendChild(function(){var e=document.createElement("div");return e.innerHTML="Hello webpack",e}())}});//# sourceMappingURL=main.014ac9aa420264da48eb.js.map

We can see that the code is basically unreadable under the packaging and compression of webpack. Therefore, we need to add the debugging plug-in to fix bugs in the production environment.

Npm start

MacBook-Pro-15:webpack zhushuangquan$ npm start> webpack@1.0.0 start /Users/zhushuangquan/Documents/code/webpack> webpack-dev-server --open --config webpack.dev.jsclean-webpack-plugin: /Users/zhushuangquan/Documents/code/webpack/dist has been removed.Project is running at http://localhost:8080/webpack output is served from /Content not from webpack is served from ./distwebpack: wait until bundle finished: /Hash: 06f20ec519d58fbd5c28Version: webpack 3.6.0Time: 1460ms            Asset    Size Chunks          Chunk Namesmain.5eb4d4e3f458c49658a2.js   852 kB    0 [emitted] [big] main         index.html 197 bytes     [emitted]     [6Um2] (webpack)/node_modules/url/util.js 314 bytes {0} [built][8o/D] (webpack)-dev-server/client/overlay.js 3.71 kB {0} [built][HPf+] (webpack)/node_modules/url/url.js 23.3 kB {0} [built][Lx3u] (webpack)/hot/log.js 1.04 kB {0} [optional] [built][Sj28] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {0} [built][TfA6] (webpack)/hot nonrecursive ^\.\/log$ 170 bytes {0} [built][U2me] (webpack)/hot/emitter.js 77 bytes {0} [built][V3KU] (webpack)-dev-server/client/socket.js 1.04 kB {0} [built][cMmS] (webpack)-dev-server/client?http://localhost:8080 7.27 kB {0} [built][gqsi] (webpack)-dev-server/node_modules/loglevel/lib/loglevel.js 7.74 kB {0} [built]  [0] multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js 40 bytes {0} [built][gt+Q] (webpack)-dev-server/node_modules/ansi-regex/index.js 135 bytes {0} [built][lVK7] ./src/index.js 184 bytes {0} [built][p7Vd] (webpack)/node_modules/punycode/punycode.js 14.7 kB {0} [built][pEPF] (webpack)/node_modules/querystring-es3/index.js 127 bytes {0} [built]  + 73 hidden modulesChild html-webpack-plugin for "index.html":   1 asset  [3IRH] (webpack)/buildin/module.js 517 bytes {0} [built]  [DuR2] (webpack)/buildin/global.js 509 bytes {0} [built]  [M4fF] ./node_modules/lodash/lodash.js 540 kB {0} [built]  [a/t9] ./node_modules/html-webpack-plugin/lib/loader.js!./node_modules/html-webpack-plugin/default_index.ejs 538 bytes {0} [built]webpack: Compiled successfully.

We can see that a webpage with the Hello webpack content opened is on port 8080. When we modify the file, the webpage will be automatically refreshed.

Knowledge point:

Return to the command line configuration of package. json.

"Scripts": {// command line tool "test": "echo \" Error: no test specified \ "& exit 1", "watch ": "webpack -- progress -- watch", "start": "webpack-dev-server -- open -- config webpack. dev. js "," build ":" webpack -- config webpack. prod. js "},
  • The above npm run build => webpack. prod. js is the packaging command that executes the configuration in the production environment.
  • The preceding npm start => webpack-dev-server -- open => webpack. dev. js command executes the server commands configured in the development environment.
  • -- Config is the command used to execute the webpack configuration file. The default value is webpack. config. js.
  • The webpack command is similar to the logic of the previous gulp. The logic of copying the entry instance to the output path is also accompanied by a series of operations.
  • Webpack-dev-server -- open command is used to open the server and perform hot loading.

The above is the use and logic of webpack. It is not as complicated as you think. It can be said that it is simple. You can get started with webpack in one day.

Since the webpack configuration is fixed code, I have packaged and uploaded it to github. You can download it if you need it.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.