Home Web Front-end JS Tutorial Upgrade webpack to version 4.0 and install webpack-cli

Upgrade webpack to version 4.0 and install webpack-cli

Jun 13, 2018 am 11:51 AM

This time I will bring you the precautions for upgrading webpack to version 4.0 and installing webpack-cli. What are the precautions for upgrading webpack to version 4.0 and installing webpack-cli? The following is a practical case, let's take a look.

1 Upgrade webpack to version 4.0 and install webpack-cli

yarn add webpack-cli global<br>yarn add webpack-cli -D
Copy after login

If you do not install webpack-cli, the following error will be reported:

The CLI moved into a separate package: webpack-cli.
Please install 'webpack-cli' in addition to webpack itself to use the CLI.
->when using npm: npm install webpack-cli -D
->when using yarn: yarn add webpack-cli -D

2 Related dependencies on some packages

Continue yarn run dev yeah!! ! An error was reported

Error: Cannot find module 'webpack/bin/config-yargs'
at Function.Module._resolveFilename (module.js:538:15)
at Function. Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object. (C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\webpack-dev-server\bin\webpack-dev-server.js:54:1)
at Module. _compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
error Command failed with exit code 1.

Solution Method: This is that the current version of webpack-dev-server does not support webpack4. Upgrade it

yarn add webpack-dev-server@3.1.1 -D //我装的是3.1.1的包
Copy after login

However, after reading a lot of information, it seems that as long as webpack-dev-server is version 3.0 or above, it seems to be compatible with Dawu. Anyway, I am 3.0. .0-alpha6 passed

3 Remove the commonchunk plugin and use webpack.optimize.SplitChunksPlugin

Execute yarn run dev again and then an error occurs. Ten thousand Pentiums in my heart There's nothing you can do about the wild horse. Let's take a look.

Error reason

Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead

Webpack4 abolished many APIs. It was troublesome to configure split public code and package third-party libraries before. Then the official did not do anything and directly abolished the previous ones and tinkered with this webpack.optimize.SplitChunksPlugin

Then Regarding the use of this plug-in, I also took a look at the official example after working on it for a long time before I got a clue. If you have a rough understanding of the original commonchunk plug-in before and go directly to the official example, you will understand. Here is the official example. Example link, the most important of which is the common-chunk-add-vendor-chunk example on how to package multiple file entries. Without further explanation, the link directly tells you how to split public code and third-party libraries.

As for packaging the runtime code webpack4 directly calls the new method ok it's done

 new webpack.optimize.RuntimeChunkPlugin({
      name: "manifest"
    }),
Copy after login

I have also posted the detailed usage of webpack.optimize.SplitChunksPlugin. Interested students can figure it out for themselves

new webpack.optimize.SplitChunksPlugin({
          chunks: "initial", // 必须三选一: "initial" | "all"(默认就是all) | "async"
          minSize: 0, // 最小尺寸,默认0
          minChunks: 1, // 最小 chunk ,默认1
          maxAsyncRequests: 1, // 最大异步请求数, 默认1
          maxInitialRequests: 1, // 最大初始化请求书,默认1
          name: function () {
          }, // 名称,此选项可接收 function
          cacheGroups: { // 这里开始设置缓存的 chunks
            priority: 0, // 缓存组优先级
            vendor: { // key 为entry中定义的 入口名称
              chunks: "initial", // 必须三选一: "initial" | "all" | "async"(默认就是异步)
              name: "vendor", // 要缓存的 分隔出来的 chunk 名称
              minSize: 0,
              minChunks: 1,
              enforce: true,
              maxAsyncRequests: 1, // 最大异步请求数, 默认1
              maxInitialRequests: 1, // 最大初始化请求书,默认1
              reuseExistingChunk: true // 可设置是否重用该chunk(查看源码没有发现默认值)
            }
          }
        }),
Copy after login

Finally paste the modified webpack.optimize.SplitChunksPlugin code

new webpack.optimize.SplitChunksPlugin({
      cacheGroups: {
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
        //打包重复出现的代码
        vendor: {
          chunks: 'initial',
          minChunks: 2,
          maxInitialRequests: 5, // The default limit is too small to showcase the effect
          minSize: 0, // This is example is too small to create commons chunks
          name: 'vendor'
        },
        //打包第三方类库
        commons: {
          name: "commons",
          chunks: "initial",
          minChunks: Infinity
        }
      }
    }),
    new webpack.optimize.RuntimeChunkPlugin({
      name: "manifest"
    }),
Copy after login

4 Upgrade the happypack plug-in! ! ! ! !

As for why the red letters are used, if you use happypack for multi-thread accelerated packaging, you must remember to upgrade happypack because I was stuck here for a long time and only found out after looking at other people's configurations. happypack is also not compatible and needs to be upgraded. . . . Post the error message at that time

TypeError: Cannot read property 'length' of undefined
at resolveLoader (C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\ happypack\lib\WebpackUtils.js:138:17)
at C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\happypack\lib\WebpackUtils.js:126:7
at C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\happypack\node_modules\async\lib\async.js:713:13

Solution: Upgrade

5 Most of the remaining problems are because the current package is incompatible with webpack4 and are posted directly here

var outputName = compilation.mainTemplate.applyPluginsWaterfall ('asset-path', outputOptions.filename, {
^

TypeError: compilation.mainTemplate.applyPluginsWaterfall is not a function
at C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\html-webpack-plugin\lib\compiler.js:81:51
at compile (C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\webpack\lib\Compiler.js:240:11)
at hooks.afterCompile.callAsync.err (C:\Users\hboxs022\Desktop\webpack-demo\webpack-demo\node_modules\webpack\lib\Compiler.js:488:14)解决办法:升级html-webpack-plugin

yarn add webpack-contrib/html-webpack-plugin -D
Copy after login

最后 extract-text-webpack-plugin和sass-loader也需要进行升级 具体我会在最后贴出我的webpack4 demo 大家看着安装哈

6 最后 配置完成测试一哈  

开发环境下

yarn run start ok 效果没问题 看一下构建时间9891ms 对比图中的webpack3 17161ms

:\Users\hboxs022\Desktop\webpack4>yarn run dev
yarn run v1.3.2
$ set NODE_ENV=dev && webpack-dev-server
Happy[js]: Version: 5.0.0-beta.3. Threads: 6 (shared pool)
(node:2060) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
i 「wds」: Project is running at http://localhost:8072/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from C:\Users\hboxs022\Desktop\webpack4\src
Happy[js]: All set; signaling webpack to proceed.
Happy[css]: Version: 5.0.0-beta.3. Threads: 6 (shared pool)
Happy[css]: All set; signaling webpack to proceed.
(node:2060) DeprecationWarning: Tapable.apply is deprecated. Call apply on the plugin directly instead
i 「wdm」: wait until bundle finished: /page/index.html
i 「wdm」: Hash: 1911cfc871cd5dc27aca
Version: webpack 4.1.1
Time: 9891ms
Built at: 2018-3-28 18:49:25
Copy after login

生产环境下

yarn run build
Copy after login

ok 第三方库jquery打包到common里了 公共js代码打包进vendor 公共样式也打包进ventor后面分离成vendor.css

目录结构也没问题 模块id也进行了固定

下面再来看看速度对比

webpack3

webpack4 是我错觉吗= =

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery+ajax读取json并排序

vue-cli安装与配置webpack

The above is the detailed content of Upgrade webpack to version 4.0 and install webpack-cli. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles