webpack3-升级-webpack4踩坑记录

11次阅读

共计 4542 个字符,预计需要花费 12 分钟才能阅读完成。

本篇不包含所有坑,暂时只记录自己踩到的部分坑

一. 安装

安装 webpack4 最新版本

npm install --save-dev webpack@4 

安装新增依赖 webpack-cli

这个在 webpack3 中,webpack 本身和它的 CLI 是在同一个包中,webpack4 中将两个分开管理。

npm install --save-dev webpack-cli

二. 运行

执行本地打包以及运行操作

npm run build:dll
npm run start

记得添加 mode

用来告知 webpack 使用相应环境的内置优化

module.exports = {mode: 'production' // 或者 'development'};

其中遇到的报错:

1.Error:webpack.optimize.UglifyJsPlugin has been removed,pleaseuseconfig.optimization.minimizeinstead.

UglifyJsPlugin 是用来对 js 文件进行压缩

webpack4 中 UglifyJsPlugin 被废除,需要安装新的插件 uglifyjs-webpack-plugin 进行替换,见官方文档

安装uglifyjs-webpack-plugin

npm install uglifyjs-webpack-plugin --save-dev 

更改 webpack.dll.config.js || webpack.prod.config.js

去除

-  new webpack.optimize.UglifyJsPlugin({
-    compress: {
-      warnings: false
-    },
-    mangle: {
-      safari10: true,
-    },
-    output: {
-      comments: false,
-      ascii_only: true,
-    },
-    sourceMap: false,
-    comments: false
-  }),

添加

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
...
optimization: { // 与 entry 同级
    minimizer: [
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: false,
          mangle: true,
          output: {comments: false,},
        },
        sourceMap: false,
      })
    ]   
},
  

注意:uglifyjs-webpack-plugin更多的配置请参考详细配置

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

CommonsChunkPlugin 主要是用来提取第三方库和公共模块

CommonsChunkPlugin 已被移除,用 splitChunks 替代,见官方文档

更改 webpack.base.config.js

去除

// new webpack.optimize.CommonsChunkPlugin({
//   children: true,
//   async: true,
//   minChunks: 2,
// }),

添加

optimization: {
    splitChunks: {
      chunks: 'async',
      minChunks: 2,
    },
  },

注意:splitChunks更多的配置请参考详细配置

3.compilation.mainTemplate.applyPluginsWaterfall is not a function

更新 html-webpack-plugin 到最新版本

npm install html-webpack-plugin@latest --save-dev

4.Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

这个最后解决方式是用 mini-css-extract-plugin 替代。

我记录下自己更新这个的过程,以下前半部分可以直接跳过。

  1. 更新 extract-webpack-plugin 到最新版本
npm install --save-dev extract-text-webpack-plugin@4.0.0-beta.0

继续报错

Path variable [contenthash] not implemented in this context: static/css/style.[contenthash].css

在之前版本中我们使用 extract-text-webpack-plugin 来提取 CSS 文件,不过在 webpack 4.x 中则应该使用 mini-css-extract-plugin 来提取 CSS 到单独文件中

更改如下

这是基于 webpack 3.0

const utils = require('./utils')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
    //...
    new ExtractTextPlugin({filename: utils.assetsPath('css/[name].[contenthash:7].css')
    })
}

基于 webpack 4.0

const utils = require('./utils')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
    //...
    new MiniCssExtractPlugin({filename: utils.assetsPath('css/[name].[contenthash:7].css')
    })
}

css 以及 mini-css-extract-plugin 的 rule 配置

module: {
    rules: [
      {test: /\.(css|less)$/,
        use: [
          {loader: MiniCssExtractPlugin.loader,},
          {
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[local]'
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              plugins: () => [require('postcss-flexbugs-fixes'),
                autoprefixer({
                  browsers: [
                    '>1%',
                    'last 4 versions',
                    'Firefox ESR',
                    'not ie < 9', // React doesn't support IE8 anyway
                  ],
                  flexbox: 'no-2009',
                }),
              ],
            }
          },
          {
            loader: 'less-loader',
            options: {modifyVars: theme}
          }
        ]

      },
    ],
  },

5.TypeError: webpack.optimize.DedupePlugin is not a constructor

DedupePlugin是用来查找相等或近似的模块,避免在最终生成的文件中出现重复的模块

已经被废除,删除即可,见官网

6.最后还有一个大坑

offline-plugin插件,可以用来对多页面应用进行缓存。这个插件的报错同以上 UglifyJsPlugin 的报错。

只需要更新到最新版本即可。

以下记录踩坑过程。

Error:webpack.optimize.UglifyJsPlugin has been removed,pleaseuseconfig.optimization.minimizeinstead.

因此导致我,删了好几次 UglifyJsPlugin 以及 uglifyjs-webpack-plugin 相关的所有代码,然后依然报错。

又以为是缓存问题,我重启了 vscode,重启了终端,电脑也尝试重启一遍,依然报错。

最后逐行注释代码,运行打包操作,发现是 offline-plugin 插件的问题。

问题所在:offline-plugin5.0 以前的版本会带有 webpack.optimize.UglifyJsPlugin 操作,最新的应该做了些处理。

详情参考

最后处理方式,更新 offline-plugin 到最新的版本

npm install offline-plugin --save-dev

三、新增 TypeScript 的打包

安装

npm install --save-dev typescript ts-loader

添加 tsconfig.json 文件

可以利用 ts 初始化命令自动添加

tsc --init

也可以手动新增文件。

其中配置详情如下,具体查阅 tsconfig.json 配置详情

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
  },
  "module": "ESNext",
  "exclude": ["node_modules"]
}

配置 webpack 处理 TypeScript, 主要更改点:

  1. 添加 rule
  2. 添加需要处理的文件后缀,’.ts’、’.tsx’ 等
rules: [
  {
    test: /\.tsx?$/,
    use: 'ts-loader',
    exclude: /node_modules/
  }
]
resolve: {extensions: [ '.tsx', '.ts', '.js']
},

测试文件 TestTsLoader.tsx

用来检测是否配置成功,导入相应页面即可测试。实测 ok

import * as React from "react"

interface TsProps {
  name: string
  company: string
}

export default class TestTsLoader extends React.Component<TsProps, {}> {render() {
    return (
      <h1>
        Hello, I am {this.props.name}, I in {this.props.company} now!
      </h1>
    )
  }
}

参考资料

1.https://blog.csdn.net/harsima…
2.https://www.typescriptlang.or…
3.https://webpack.docschina.org…

四. 再推荐一个 npm script 命令优化插件 better-npm-run

参考:

1.https://www.jianshu.com/p/710…
2.https://www.npmjs.com/package…

正文完
 0