search
HomeWeb Front-endJS TutorialSummary of knowledge points about webpack2

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='brush:php;toolbar:false;'>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='brush:php;toolbar:false;'>// 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='brush:php;toolbar:false;'>// 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
Web Speech API开发者指南:它是什么以及如何工作Web Speech API开发者指南:它是什么以及如何工作Apr 11, 2023 pm 07:22 PM

​译者 | 李睿审校 | 孙淑娟Web Speech API是一种Web技术,允许用户将语音数据合并到应用程序中。它可以通过浏览器将语音转换为文本,反之亦然。Web Speech API于2012年由W3C社区引入。而在十年之后,这个API仍在开发中,这是因为浏览器兼容性有限。该API既支持短时输入片段,例如一个口头命令,也支持长时连续的输入。广泛的听写能力使它非常适合与Applause应用程序集成,而简短的输入很适合语言翻译。语音识别对可访问性产生了巨大的影响。残疾用户可以使用语音更轻松地浏览

如何使用Docker部署Java Web应用程序如何使用Docker部署Java Web应用程序Apr 25, 2023 pm 08:28 PM

docker部署javaweb系统1.在root目录下创建一个路径test/appmkdirtest&&cdtest&&mkdirapp&&cdapp2.将apache-tomcat-7.0.29.tar.gz及jdk-7u25-linux-x64.tar.gz拷贝到app目录下3.解压两个tar.gz文件tar-zxvfapache-tomcat-7.0.29.tar.gztar-zxvfjdk-7u25-linux-x64.tar.gz4.对解

web端是什么意思web端是什么意思Apr 17, 2019 pm 04:01 PM

web端指的是电脑端的网页版。在网页设计中我们称web为网页,它表现为三种形式,分别是超文本(hypertext)、超媒体(hypermedia)和超文本传输协议(HTTP)。

web前端和后端开发有什么区别web前端和后端开发有什么区别Jan 29, 2023 am 10:27 AM

区别:1、前端指的是用户可见的界面,后端是指用户看不见的东西,考虑的是底层业务逻辑的实现,平台的稳定性与性能等。2、前端开发用到的技术包括html5、css3、js、jquery、Bootstrap、Node.js、Vue等;而后端开发用到的是java、php、Http协议等服务器技术。3、从应用范围来看,前端开发不仅被常人所知,且应用场景也要比后端广泛的太多太多。

web前端打包工具有哪些web前端打包工具有哪些Aug 23, 2022 pm 05:31 PM

web前端打包工具有:1、Webpack,是一个模块化管理工具和打包工具可以将不同模块的文件打包整合在一起,并且保证它们之间的引用正确,执行有序;2、Grunt,一个前端打包构建工具;3、Gulp,用代码方式来写打包脚本;4、Rollup,ES6模块化打包工具;5、Parcel,一款速度极快、零配置的web应用程序打包器;6、equireJS,是一个JS文件和模块加载器。

深入探讨“高并发大流量”访问的解决思路和方案深入探讨“高并发大流量”访问的解决思路和方案May 11, 2022 pm 02:18 PM

怎么解决高并发大流量问题?下面本篇文章就来给大家分享下高并发大流量web解决思路及方案,希望对大家有所帮助!

Python轻量级Web框架:Bottle库!Python轻量级Web框架:Bottle库!Apr 13, 2023 pm 02:10 PM

和它本身的轻便一样,Bottle库的使用也十分简单。相信在看到本文前,读者对python也已经有了简单的了解。那么究竟何种神秘的操作,才能用百行代码完成一个服务器的功能?让我们拭目以待。1. Bottle库安装1)使用pip安装2)下载Bottle文件https://github.com/bottlepy/bottle/blob/master/bottle.py2.“HelloWorld!”所谓万事功成先HelloWorld,从这个简单的示例中,了解Bottle的基本机制。先上代码:首先我们从b

ASGI解释:Python Web开发的未来ASGI解释:Python Web开发的未来Apr 12, 2023 pm 10:37 PM

​译者 | 李睿审校 | 孙淑娟Python Web应用程序长期以来一直遵循Web服务器网关接口(WSGI)标准,该标准描述了它们如何与Web服务器通信。WSGI最初于2003年推出,并于2010年更新,仅依赖于Python2.2版本中原生可用的、易于实现的功能。因此, WSGI迅速融入了所有主要的Python Web框架,并成为Python Web开发的基石。快进到2022年。Python2已经过时,Python现在具有处理网络调用等异步操作的原生语法。WSGI和其他默认假定同步行为的标准无法

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft