[to] those pits that have been trampled when using Webpack

Source: Internet
Author: User

The process of using webpack is a process of constantly entering and out of pits. Look back at the road, all the way is a pit! Now I have to go through those pits, you crossing blessed ~

At the end of the article is the dependent version information I used, and if you find that the problem is inconsistent with what I described in this article, I can see if the version is different from the one I used.

One, the difference between Mac platform and Windows platform causes problem 1, the difference on the path

When configuring the entry option, I configure this:

entry: {    main: __dirname + ‘/src/index.js‘}

This is not a problem to write on your Mac, but you will get an error under windows:

ERROR in Entry module not found: Error: Can‘t resolve ‘d:\demo\config/src/index.js‘ in ‘d:\demo‘

This is because there are differences in the paths of the two platforms. Mac is / , while Windows is \ .

The solution is:

const path = require(‘path‘);const entryPath = path.resolve(__dirname, ‘/src/index.js‘);entry: {    main: entryPath}
2. Set the difference of node environment variable

On a Mac, you can configure it in Package.json:

"scripts": {     "build":"NODE_ENV=production && ..."}

But it's not working in Windows. To solve this problem, you need to use the Cross-env module.

Install it first:

npm i cross-env --save-dev

Then the above configuration can be changed to:

"scripts": {     "build":"./node_modules/.bin/cross-env NODE_ENV=production && ..."}
Second, the pit in the Babel configuration

For Babel configuration, there are two issues that can be easily seen:

1, easy in the Presets configuration when a layer less [].

The configuration is problematic in this way:

presets: [   ‘es2015‘,   ‘react‘,   ‘stage-2‘],

This will be an error when packing:

Using removed Babel 5 option: foreign.modules -Use the corresponding module transform plugin in the `plugins` option

Babel 6, we must pack this layer [], the complete should be written as follows.

{    test: /\.(js|es|es6|jsx)$/,    use: [        {            loader: ‘babel-loader‘,            options: {               presets: [                   [‘es2015‘, {modules: false, loose: true}],                   [‘react‘],                   [‘stage-2‘]               ],               plugins: [                   [‘transform-runtime‘]               ],               comments: false,               cacheDirectory: true            }        },        {            loader: ‘eslint-loader‘,            options: {                configFile: eslintConfigPath            }        }    ],    exclude: excludeReg},

One of the modules: false configuration items is to tell es2015 preset to avoid compiling the import statements into Commonjs, so webpack is good to do the tree shaking.

2. Easily ignore the Babel statement in the. vue file for transcoding.

As configured above, transcoding of JavaScript files, such as. js,. es,. Es6,. Jsx, is not a problem, but these configurations do not affect the. vue file. However, when the. vue file is compiled, Vue-loader will load the. BABELRC configuration by default. Therefore, we should write these Babel configurations to the. babelrc file for ease of sharing with the. Vue file compilation. Make these configuration items useful when compiling JavaScript files and. vue files.

So, we pull out the Babel configuration options and put them in the. bablerc file with the code:

{    presets: [        ["react"],        [            "es2015", {"modules": false, "loose": true}        ],        ["stage-2"]    ],    plugins: [        ["transform-runtime"]    ],    comments: false}

The modified Babel-loader configuration is:

{    test: /\.(js|es|es6|jsx)$/,    use: [        {            loader: ‘babel-loader‘,            options: {               cacheDirectory: true            }        },        {            loader: ‘eslint-loader‘,            options: {                configFile: eslintConfigPath            }        }    ],    exclude: excludeReg},
Third, the processing of non-modular libraries, such as Zepto

For libraries that are not modular, if they are direct import , they will get an error when Webpack is packaged. See: Https://juejin.im/entry/588ca3018d6d81006c237c85

The solution is to add the following configuration items under module rules:

{    test: require.resolve(‘zepto‘),    loader: ‘exports-loader?window.Zepto!script-loader‘}

Where require.resolve()  Nodejs is used to find the module location, return the module's entry file, such as Zepto./node_modules/zepto/dist/zepto.js.

In addition, two loader are used here, and we need to install them first:

npm i --save-dev script-loader exports-loader
Four, Clean-webpack-plugin root configuration items can not be less
var CleanWebpackPlugin = require(‘clean-webpack-plugin‘);new CleanWebpackPlugin(baseConfig.output.path, {    root: rootPath,    verbose: true}),

This root configuration item cannot be missing, otherwise the following prompt appears, and the clean operation is skipped.

clean-webpack-plugin: ...\build is outside of the project root. Skipping...

In addition, this verbose configuration item is quite puzzling. The meaning of verbose is long, wordy. The actual meaning is the write logs to console, that is, whether to output log to the terminal.

V. The Pit of Extract-text-webpack-plugin

1, currently can not use the web-dev-server when using the plug-in

When using Web-dev-server, do not use Extract-text-webpack-plugin, not currently supported. See also: https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/384

2, if webpack in multiple configuration files (such as Webpack.base.config.js, Webpack.dev.config.js, webpack.prod.config.js, etc.), when using the Object.assign merge, The latter profile overwrites the plugins option of the previous file, or mistakenly places the plugins option under module incorrectly in the configuration file. The following error will be reported due to the lack of configuration of the Extract-text-webpack-plugin plugin under the plugins option, and it is difficult to troubleshoot the cause of errors without careful observation:

Module build failed: Error: "extract-text-webpack-plugin" loader is used without the corresponding plugin

See also: HTTPS://GITHUB.COM/WEBPACK/EXTRACT-TEXT-WEBPACK-PLUGIN/ISSUES/50

Six, when using Less-loader to install the less module, install the Less-loader module separately, will not automatically install less module

Use Less-loader to install the less module at the same time, otherwise it will report an error:

Module build failed: Error: Cannot find module ‘less‘。

Less-loader need to rely less to achieve. Because less in npm3.0+ is not automatically installed with Less-loader.

Vii. misuse of hash, Chunkhash, Contenthash

These three "ghosts", it is really easy to make people silly points are not clear!

For the distinction between hash and chunkhash, see: http://www.cnblogs.com/ihardcoder/p/5623411.html

Chunkhash is a change in the content of a particular chunk, that is, the hash value calculated from the content of a particular chunk. Webpack when calculating chunkhash, it is calculated separately according to the entry file (entry). When a portion of the chunk changes (either JS or CSS), the Chunkhash is recalculated. The Webpack uses the Nodejs built-in crypto module to calculate the Chunkhash. Each chunk resource generates Chunkhash associated with its content.

The hash is generated with compilation, and when any file in the project is changed, a new compilation is created, and the corresponding hash value is updated. A hash can be understood as the hash value of a project's overall file, not a specific chunk. That is, it is a hash that is affected by all chunks. Each compilation generates a unique hash, but all the resources are in the same hash, and the need to persist the cache cannot be completed.

Some people say that, in the hot update mode, the hash will be changed to Chunkhash, vendors file will become undefined, tried many kinds of communication format, still can not achieve the purpose. The final discovery is only true in the Webpack hot update mode, and because the development environment can ignore versioning, splitting the configuration in both environments solves the problem.

Do not use [Chunkhash]/[hash]/[contenthash] in the development environment, because you do not need to do persistent caching in the development environment, and this will increase the compilation time, the development environment with [name].

Extract-text-webpack-plugin provides another hash value: Contenthash. As the name implies, Contenthash represents the hash value of the content of the text file, which is the hash value of only the style file.

Because it can be configured on the production environment:

new ExtractTextWebpackPlugin({    filename: ‘css/[name].[contenthash].css‘,    allChunks: true})

You should also generate a plug-in for a stable module ID on the production environment configuration:

new webpack.HashedModuleIdsPlugin(),
Eight new webpack.optimize.UglifyJsPluginError when packing

Note that the current version of Uglifyjsplugin has the following error when packaging:

ERROR in build.js from UglifyJsSyntaxError:Unexpected token punc «(», expected punc «:»

The reason is that the plug-in relies on UGLIFY-JS, but the current version of UGLIFY-JS is not supported ES6 code compression, the solution is:

Add the following dependencies to the Package.json devdependencies, and then re-execute them again npm install .

"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"

See also: Https://github.com/webpack-contrib/uglifyjs-webpack-plugin

 New Webpack.optimize.UglifyJsPlugin ({mangle: {//Exclude object names that you do not want to compress except: [' $ ', ' exports ', ' require ', ' modul E ']}, Compress: {//Http://lisperator.net/uglifyjs/compress Warnings:false,//warn about potent Ially Dangerous Optimizations/code conditionals:true,//optimize if-s and conditional expressions unused: True,//drop unused variables/functions comparisons:true,//optimize comparisons sequences:true, Join consecutive statements with the "comma Operato" dead_code:true,//Discard unreachable code discards unused code Evaluate:true,//Evaluate constant expressions Join_vars:true,//join VAR declarations if _return:true//optimize if-s followed by return/continue}, Output: {//Https://github.com/mishoo/Ugli Fyjs2/blob/master/lib/output.js Comments:false}, Sourcemap:false//Map the location of the error message to the module. This slows down the speed of compilation. Used only in the development environment. }),

By the way, note the configuration of the compression options above uglifyjsplugin.

Unused and Dead_code are the two options that allow tree shaking.

Nine new webpack.optimize.CommonsChunkPluginPackaged public files forget to introduce or introduce errors caused by incorrect order

Note: If you use Commonschunkplugin to generate a common file, but the page does not introduce commonschunkplugin generated public files or the location of the introduction of this common file is not in the other Webpack packaged JS file, When you browse the page, an error will appear:

Uncaught ReferenceError: webpackJsonp is not defined

To ensure that these files are introduced in the correct order, you need to include this configuration entry in the configuration entry for the Html-webpack-plugin plugin:

// necessary to consistently work with multiple chunks via CommonsChunkPluginchunksSortMode: ‘dependency‘

Attached: List of dependent module version information

"Dependencies": {"Babel-polyfill": "^6.23.0", "Element-ui": "^1.2.5", "es6-promise": "^4.1.0", "Vue": "^2.2.4     "," Vue-router ":" ^2.3.0 "," Vuex ":" ^2.2.1 "," Zepto ":" ^1.2.0 "}," Devdependencies ": {" autoprefixer ":" ^6.6.1 ", "Babel-core": "^6.22.1", "Babel-loader": "^6.2.10", "Babel-plugin-transform-runtime": "^6.23.0", "Babel-prese t-es2015 ":" ^6.22.0 "," Babel-preset-es2015-webpack ":" ^6.4.3 "," Babel-preset-latest ":" ^6.22.0 "," Babel-preset-re    Act ":" ^6.23.0 "," babel-preset-stage-2 ":" ^6.22.0 "," Clean-webpack-plugin ":" ^0.1.15 "," Css-loader ":" ^0.26.1 ", "Eslint": "^3.14.0", "Eslint-config-airbnb": "^14.0.0", "Eslint-loader": "^1.6.1", "eslint-plugin-html": "^2.0." 1 "," Eslint-plugin-import ":" ^2.2.0 "," eslint-plugin-jsx-a11y ":" ^3.0.2 "," eslint-plugin-react ":" ^6.9.0 "," ex Ports-loader ":" ^0.6.4 "," Expose-loader ":" ^0.7.3 "," Extract-text-webpack-plugin ":" ^2.0.0-beta.5 "," File-loader " : "^0.9.0", "Glob": "^7.1.1 "," Html-loader ":" ^0.4.5 "," Html-webpack-plugin ":" ^2.26.0 "," Ink-docstrap ":" ^1.3.0 "," jsdoc-webpack-p Lugin-v2 ":" 0.0.1 "," less ":" ^2.7.2 "," Less-loader ":" ^2.2.3 "," Node-sass ":" ^4.3.0 "," path ":" ^0.12.7 "," p Ostcss-loader ":" ^1.2.2 "," Sass-loader ":" ^4.1.1 "," Script-loader ":" ^0.7.0 "," Style-loader ":" ^0.13.1 "," Ugli Fy-js ":" Git+https://github.com/mishoo/uglifyjs2.git#harmony "," Url-loader ":" ^0.5.7 "," Vue-loader ":" ^11.1.4 "," Vue-template-compiler ":" ^2.2.4 "," Webpack ":" ^2.2.1 "," Webpack-dev-server ":" ^2.2.0 "

[to] those pits that have been trampled when using webpack

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.