Home  >  Article  >  Web Front-end  >  Summary of knowledge points about webpack2

Summary of knowledge points about webpack2

巴扎黑
巴扎黑Original
2017-07-18 18:42:141250browse

This article's github repository:

Migrate from v1 to v2

webpack1.x upgrade 2.x

1.module.loaders changed to module.rules

The old loaders are replaced by new rules, which allow configuration of loaders and more.

module: {
- loaders: [
+ rules: [
{ test: /\.css$/,
- loaders: [
+ use: [
{ modules: true
} }
]
},
{test:/\.jsx $/, loader: "babel-loader", // do not used "use" jee
Options: {// ...
}
}
]
}


In the above writing method, Rule.loader is the abbreviation of Rule.use: [ { loader } ].

1. Configuration type

In webpack1, configuration is mainly done by exporting a single

object

. For example, the following configuration:

// webpack1 导出方式module.export = {entry : 'app.js',output : { */... */},/* ... */};
In webpack2, there are three ways to flexibly configure it for different scenarios.

1.1 Export different configuration files through different environment variables

// 可以有两种方式传递当前值,一种是简单传递字符串,另外一种则是传递一个对象// 例如: webpack --env production 控制台打印的就是 'production',是一个字符串// 而当这样调用时:webpack --env.production --env.size 60,控制台打印的就是 { production : true, size : 60 }var path = require('path'),webpack = require('webpack'),UglifyJsPlugin = new webpack.optimize.UglifyJsPlugin(),plugins = [];module.exports = function(env) {console.log(env);
  if (env === 'production') {plugins.push(UglifyJsPlugin);}return {entry : path.resolve(__dirname, 'js/app.js'),output : {path : path.resolve(__dirname, 'build'),filename : '[name].bundle.js'},module : {rules : [{ test : /\.js|\.jsx$/, loader : 'babel-loader', options : {presets : ["es2015", "react"]} },{ test : /\.css$/,use : ['style-loader', 'css-loader']},{test : /\.less$/,use : ['style-loader', 'css-loader', 'less-loader']}]},plugins : plugins};}// 在package.json中配置两个命令{"dev" : "webpack","build" : "webpack --env production"}

For specific production environment construction methods, please refer to the official website production

1.2 Export through promise Configuration file

The application scenario of this method is that in some cases, we temporarily cannot get the configuration parameters required for the configuration file, such as the file name that needs to be configured, etc. Perhaps this is an asynchronous operation. , through promise, we can get the configuration variables after the asynchronous operation, and then execute the configuration file.

// 在这种情况下,1秒之后会返回配置文件并且执行var path = require('path');module.exports = () => {return new Promise((resolve, reject) => {console.log('loading configuration ...');setTimeout(() => {console.log('loading completed!');resolve({entry : path.resolve(__dirname, 'js/app.js'),output : {path : path.resolve(__dirname, 'build'),filename : '[name].bundle.js'},module : {rules : [{ test : /\.js|\.jsx$/, loader : 'babel-loader', options : {presets : ["es2015", "react"]} },{ test : /\.css$/,use : ['style-loader', 'css-loader']},{test : /\.less$/,use : ['style-loader', 'css-loader', 'less-loader']}]},});}, 1000);});}

1.3 Packing multiple configuration files at the same time

Webpack1 can only export a single configuration file. In webpack2, multiple configuration files can be packaged at the same time, which means that you can When packaging multiple entry files, you no longer need to execute packaging commands for each individual page when packaging multiple pages.

// config-amd.jsvar path = require('path');module.exports = {entry : path.resolve(__dirname, 'js/app.js'),output : {path : path.resolve(__dirname, 'build'),filename : '[name].amd.js',libraryTarget : 'amd'},module : {rules : [{ test : /\.js|\.jsx$/, loader : 'babel-loader', options : {presets : ["es2015", "react"]} },{ test : /\.css$/,use : ['style-loader', 'css-loader']},{test : /\.less$/,use : ['style-loader', 'css-loader', 'less-loader']}]}};// config-commonjs.jsvar path = require('path');module.exports = {entry : path.resolve(__dirname, 'js/app.js'),output : {path : path.resolve(__dirname, 'build'),filename : '[name].commonjs.js',libraryTarget : 'commonjs'},module : {rules : [{ test : /\.js|\.jsx$/, loader : 'babel-loader', options : {presets : ["es2015", "react"]} },{ test : /\.css$/,use : ['style-loader', 'css-loader']},{test : /\.less$/,use : ['style-loader', 'css-loader', 'less-loader']}]}};// webpack.config.jsvar configAmd = require('./config-amd.js'),configCommonjs = require('./config-commonjs.js');module.exports = [
    configAmd,configCommonjs
]

2. resolve related

2.1 extensions suffix extension

In webpack2, there is no need to write an empty string by default, if this is not configured option, the default suffix is ​​

['.js', '.json']

, so you can write ## directly when you need to use

import 'some.js'

#import 'some'Just fine. If you do not want to enable automatic suffix, you need to configure enforceExtension: true in resolve

, for example:

<pre class="sourceCode javascript">var path = require(&amp;#39;path&amp;#39;);module.exports = {entry : // ....,// ...resolve : {enforceExtension : true}};</pre>This At this time, if js/text.js

is referenced in
js/app.js
, an error will be reported

<pre class="sourceCode javascript">// Errorimport &amp;#39;./text&amp;#39;;// Rightimport &amp;#39;./text.js&amp;#39;;</pre>2.2 root/fallback/ modulesDirectories file positioning

Configuring these three properties in
webapck1 resolve
tells webpack the folder that must be searched for when introducing modules. In webpack2, it is directly replaced with a separate Attribute

modules

, the default priority is to search

node_modules (note that this is a relative position)<pre class="sourceCode javascript">// configresolve: {// root : path.join(__dirname, &quot;src&quot;) webpack1方式modules : [path.join(__dirname, &quot;src&quot;), // 优先于node_modules/搜索&quot;node_modules&quot;]}// 修改 js/app.js// 在js文件夹中,增加一个lodash.js,如果按照上面的配置了modules,则会优先加载我们自己的lodash库import &amp;#39;../css/style.less&amp;#39;;import _ from &amp;#39;lodash&amp;#39;;console.log(_.isObject([1, 2, 3]));document.getElementById(&amp;#39;container&amp;#39;).textContent = &amp;#39;APP&amp;#39;;// js/lodash.jsexport default {isObject(a) {console.log(&amp;#39;this is my lodash library!&amp;#39;);return a &amp;&amp; typeof a === &amp;#39;object&amp;#39;;}}</pre>

得到的结果如下图:

Summary of knowledge points about webpack2

3. module相关

3.1 module.rules替换module.loaders

The old loader configuration was superseded by a more powerful rules system, which allows configuration of loaders and more. For compatibility reasons, the old module.loaders syntax is still valid and the old names are parsed. The new naming conventions are easier to understand and are a good reason to upgrade the configuration to using module.rules.

大意就是新的命名更容易理解(反正对于我来说就是换了个英文单词:-D),同时还会兼容老的方式,也就是说,你照样写module.loaders还是可以的。

module : {// webpack1 way// loaders : [...]// nowrules : [
        ...
    ]}

3.2 module[*].loader写法

如果需要加载的模块只需要一个loader,那么你还是可以直接用loader这个关键词;如果要加载的模块需要多个loader,那么你需要使用use这个关键词,在每个loader中都可以配置参数。代码如下:

module : {rules : [{ test : /\.js|\.jsx$/, loader : &#39;babel-loader&#39; },  /* 如果后面有参数需要传递到当前的loader,则在后面继续加上options关键词,例如:          {             test : /\.js|\.jsx$/,             loader : &#39;babel-loader&#39;,             options : { presets : [ &#39;es2015&#39;, &#39;react&#39; ] }           }        */  {test : /\.css$/,// webpack1 way// loader : &#39;style!css&#39;  use : [ &#39;style-loader&#39;, &#39;css-loader&#39; ]},{test : /\.less$/,use : [&#39;style-loader&#39;,     // 默认相当于 { loader : &#39;style-loader&#39; }{loader : &#39;css-loader&#39;,options : {modules : true}},&#39;less-loader&#39;]}]}

3.2 取消自动添加-loader后缀

之前写loader通常是这样的:

loader : &#39;style!css!less&#39;// equals toloader : &#39;style-loader!css-loader!less-loader&#39;

都自动添加了-loader后缀,在webpack2中不再自动添加,如果需要保持和webpack1相同的方式,可以在配置中添加一个属性,如下:

module.exports = {...resolveLoader : {moduleExtensions : ["-loader"]}}// 然后就可以继续这样写,但是官方并推荐这样写// 不推荐的原因主要就是为了照顾新手,直接写会让刚接触的童鞋感到困惑// github.com/webpack/webpack/issues/2986use : [ &#39;style&#39;, &#39;css&#39;, &#39;less&#39; ]

3.3 json-loader内置啦

如果要加载json文件的童鞋再也不需要配置json-loader了,因为webpack2已经内置了。

4. plugins相关

4.1 UglifyJsPlugin 代码压缩插件

压缩插件中的warningssourceMap不再默认为true,如果要开启,可以这样配置

plugins : [new UglifyJsPlugin({souceMap : true,warnings : true})
]

4.2 ExtractTextWebapckPlugin 文本提取插件

主要是写法上的变动,要和webpack2配合使用的话,需要使用version 2版本

// webpack1 waymodules : {loaders : [{ test : /\.css$/, loader : ExtractTextPlugin.extract(&#39;style-loader&#39;, &#39;css-loader&#39;, { publicPath : &#39;/dist&#39; })}   
    ]},plugins : [new ExtractTextPlugin(&#39;bunlde.css&#39;, { allChunks : true, disable : false })
]// webapck2 waymodules : {rules : [{ test : /\.css$/, use : ExtractTextPlugin.extract({fallback : &#39;style-loader&#39;,use : &#39;css-loader&#39;,publicPath : &#39;/dist&#39;})}]},plugins : [new ExtractTextPlugin({filename : &#39;bundle.css&#39;,disable : false,allChunks : true})
]

5. loaders的debug模式

在webpack1中要开启loaders的调试模式,需要加载debug选项,在webpack2中不再使用,在webpack3或者之后会被删除。如果你想继续使用,那么请使用以下写法:

// webpack1 waydebug : true// webapck2 way // webapck2将loader调试移到了一个插件中plugins : [new webpack.LoaderOptionsPlugin({debug : true})
]

6. 按需加载方式更改

6.1 import()方式

在webpack1中,如果要按需加载一个模块,可以使用require.ensure([], callback)方式,在webpack2中,ES2015 loader定义了一个import()方法来代替之前的写法,这个方法会返回一个promise.

// 在js目录中新增一个main.js// js/main.jsconsole.log(&#39;main.js&#39;);// webpack1 wayrequire.ensure([], function(require) {var _ = require(&#39;./lodash&#39;).default;console.log(_);console.log(&#39;require ensure&#39;);console.log(_.isObject(1));});// webpack2 way// 采用这种方式,需要promise 的 polyfill// 两种方式:// 1. npm install es6-promise --save-dev//    require(&#39;es6-promise&#39;).polyfill();//// 2. babel方式,在webpack中配置babel插件//    npm install babel-syntax-dynamic-import --save-dev//    options : {//        presets : [&#39;es2015&#39;],//        plugins : [&#39;syntax-dynamic-import&#39;]//    }import(&#39;./lodash&#39;).then(module => {let _ = module.default;console.log(_);console.log(&#39;require ensure&#39;);console.log(_.isObject(1));});

会得到的chunk文件,如下图:

Summary of knowledge points about webpack2

Summary of knowledge points about webpack2-console

6.2 动态表达式

可以动态的传递参数来加载你需要的模块,例如:

function route(path, query) {return import(`./routes/${ path }/route`)
        .then(route => { ... })}

7. 热替换更加简单

webpack2中提供了一种更简单的使用热替换功能的方法。当然如果要用node启动热替换功能,依然可以按照webpack1中的方式。

npm install webpack-dev-server --save-dev// webpack.config.jsmodule.exports = {// ...,devServer : {contentBase : path.join(__dirname, &#39;build&#39;),hot : true,compress : true,port : 8080,publicPath : &#39;/build/&#39;},plugins : [new webpack.HotModuleReplacementPlugin()
    ]}

谈谈V2版本

主要是介绍之前在webpack1中忽略的以及v2版本中新加的一些东西。

1. caching(缓存)

浏览器为了不重复加载相同的资源,因此加入了缓存功能。通常如果请求的文件名没有变的话,浏览器就认为你请求了相同的资源,因此加载的文件就是从缓存里面拿取的,这样就会造成一个问题,实际上确实你的文件内容变了,但是文件名没有变化,这样还是从缓存中加载文件的话,就出事了。

那么,之前传统的做法就是给每个文件打上加上版本号,例如这样:

app.js?version=1app.css?version=1

每次变动的时候就给当前的版本号加1,但是如果每次只有一个文件内容变化就要更新所有的版本号,那么没有改变的文件对于浏览器来说,缓存就失效了,需要重新加载,这样就很浪费了。那么,结合数据摘要算法,版本号根据文件内容生成,那么现在的版本可能是这样的。

// beforeapp.js?version=0add34app.css?version=1ef4a2// after// change app.js contentapp.js?versoin=2eda1capp.css?version=1ef4a2

关于怎么部署前端代码,可以查看大公司怎样开发和部署前端代码

webpack为我们提供了更简单的方式,为每个文件生成唯一的哈希值。为了找到对应的入口文件对应的版本号,我们需要获取统计信息,例如这样的:

{
  "main.js?1.1.11": "main.facdf96690cca2fec8d1.js?1.1.11",
  "vendor.js?1.1.11": "vendor.f4ba2179a28531d3cec5.js?1.1.11"}

同时,我们结合html-webpack-plugin使用的话,就不需要这么麻烦,他会自动给文件带上对应的版本。具体看法参看之前写的webpack1知识梳理,那么我们现在的配置变成了这个样子:

npm install webpack-manifest-plugin --save-dev// webpack.config.jsmodule.exports = {entry : { /* ... */ },output : {path : path.resolve(__dirname, &#39;build-init&#39;),filename : &#39;[name].[chunkhash].js&#39;,chunkFilename : &#39;[name].[chunkhash].js&#39;},module : {// ...},plugins : [new htmlWebpackPlugin({title : &#39;webpack caching&#39;}),new WebpackManifestPlugin()
    ]}

html引入情况

<!DOCTYPE html><html>
  <head><meta charset="UTF-8"><title>webpack caching</title>
  </head>
  <body>
  <div id="container"></div>
  <script type="text/javascript" src="main.facdf96690cca2fec8d1.js?1.1.11"></script><script type="text/javascript" src="vendor.f4ba2179a28531d3cec5.js?1.1.11"></script></body></html>

WARNNING:

不要在开发环境下使用[chunkhash],因为这会增加编译时间。将开发和生产模式的配置分开,并在开发模式中使用[name].js的文件名,在生产模式中使用[name].[chunkhash].js文件名。

为了使文件更小化,webpack使用标识符而不是模块名称,在编译的时候会生成一个名字为manifest的chunk块,并且会被放入到entry中。那么当我们更新了部分内容的时候,由于hash值得变化,会引起manifest块文件重新生成,这样就达不到长期缓存的目的了。webpack提供了一个插件ChunkManifestWebpackPlugin,它会将manifest映射提取到一个单独的json文件中,这样在manifest块中只需要引用而不需要重新生成,所以最终的配置是这样的:

var path = require(&#39;path&#39;),webpack = require(&#39;webpack&#39;),htmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;),ChunkManifestWebpackPlugin = require(&#39;chunk-manifest-webpack-plugin&#39;),WebpackChunkHash = require(&#39;webpack-chunk-hash&#39;);module.exports = {entry : {main : path.resolve(__dirname, &#39;js/app.js&#39;),vendor : path.resolve(__dirname, &#39;js/vendor.js&#39;)},output : {path : path.resolve(__dirname, &#39;build&#39;),filename : &#39;[name].[chunkhash].js&#39;,chunkFilename : &#39;[name].[chunkhash].js&#39;},module : {// ...},plugins : [new webpack.optimize.CommonsChunkPlugin({name : [&#39;vendor&#39;, &#39;manifest&#39;],minChunks : Infinity}),new webpack.HashedModuleIdsPlugin(),new WebpackChunkHash(),new htmlWebpackPlugin({title : &#39;webpack caching&#39;}),new ChunkManifestWebpackPlugin({filename : &#39;chunk-mainfest.json&#39;,manifestVariable : &#39;webpackManifest&#39;,inlineManifest : true})
    ]}

tips:如果还不是很明白,去对比一下加了ChunkManifestWebpackPlugin和没加的区别就可以清楚的感受到了。在本文的代码文件夹caching中可以看到这一差别

The above is the detailed content of Summary of knowledge points about webpack2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn