webpack3升级webpack4遇到的各种问题汇总

webpack3升级webpack4遇到的各种问题汇总

问题1

javascript 复制代码
var outputName=compilation.mainTemplate.applyPluginWaterfull('asset-path',outputOptions.filename,{......)

TypeError: compilation.mainTemplate.applyPluginsWaterfall is not a function

解决方法

html-webpack-plugin 版本不兼容问题
升级 npm i --save-dev html-webpack-plugin@next

问题2

javascript 复制代码
Module build failed(from ./node_modules/stylus-loader/index.js):
TypeError:cannot read property 'stylus' of undefined 

解决方法

需要将stylus-loader的版本更新到3.0.2,就可以
npm uninstall stylus-loader
npm install [email protected] --save-dev

问题3

javascript 复制代码
internal/modules/cjs/loader.js:934
Error:cannot find module 'webpack/bin/config-yargs'

解决方法

这个就是目前版本的[email protected] 不支持 webpack@4以上,需要重装一个webpack-dev-server是3.0版本以上就兼容

问题4

javascript 复制代码
\node_modules\wepbpack\lib\TemplatePathPlugin.js: 
throw new Error(
Error:Path variable[contenthash:8] not implemented in this context:static/css/[name].[contenthash:8].css
javascript 复制代码
Error: Chunk.entrypoints: Use Chunks.groupsIterable and 
filter by instanceof Entrypoint instead 

解决方法

extract-text-webpack-plugin还不能支持webpack4.0.0以上的版本。

javascript 复制代码
npm install --save-dev extract-text-webpack-plugin@next 
会下载到+ [email protected] 

注意修改如下配置

javascript 复制代码
config.plugins.push(
   new ExtractPlugin('styles.[md5:contentHash:hex:8].css')
	//将[contentHash:8].css改成[md5:contentHash:hex:8].css
 )

问题5

npm i xxx ,遇到安装包,安装直接报错,如下图

解决方法

javascript 复制代码
npm i xxx  -D  --force  // 末尾添加--force

问题6

javascript 复制代码
Uncaught TypeError: Cannot assign to read only property 'exports' 
of object '#<Object>'

解决方法

javascript 复制代码
1、npm install babel-plugin-transform-es2015-modules-commonjs -D
2、在 .babelrc 中增加一个plugins
{
	"plugins": ["transform-es2015-modules-commonjs"]
}

问题7

javascript 复制代码
Insufficient number of arguments or no entry found.

解决方法

webpack.config.js中的entry入口文件写错,注意自行修改

问题8

javascript 复制代码
Module build failed: TypeError: Cannot read property 'vue' of undefined at Object.module.exports (...\node_modules\vue-loader\lib\loader.js:61:18)

解决方法

安装[email protected]即可
npm install [email protected]

问题9

javascript 复制代码
WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment. 
You can also set it to 'none' to disable any default behavior.


解决方法

javascript 复制代码
// 给package.json文件中的scripts设置mode
"dev": "webpack --mode development",
"build": "webpack --mode production"

配置webpack.config.js文件

javascript 复制代码
onst path = require('path');
module.exports = {
    entry: path.join(__dirname, './src/index.js'),//被打包文件所在的路径
    output: {
        path: path.join(__dirname, './dist'),//打包文件保存的路径
        filename: 'main.js'
    },
    mode: 'development' // 设置mode
}

问题10

webpack3 打包用 CommonsChunkPlugin

webpack4 打包用 SplitChunkPlugin

解决方法

把webpack3的代码分割修改为 webpack4的写法即可

javascript 复制代码
示例代码:
chainWebpack(config) {
    // 使用速度分析
    config.plugin('speed-measure-webpack-plugin').use(SpeedMeasurePlugin).end()
    // 删除懒加载模块的 prefetch preload,降低带宽压力(使用在移动端)
    config.plugins.delete('prefetch')
    config.plugins.delete('preload')
    // 路径别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('components', resolve('src/components'))
      .set('pages', resolve('src/pages'))
      .set('utils', resolve('src/utils'))
    config.when(process.env.NODE_ENV !== 'development', config => {
      // 生产打包优化
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      // 打包分割
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          // axios: {
          //   name: 'chunk-axios', // split axios into a single package
          //   priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          //   test: /[\\/]node_modules[\\/]_?axios(.*)/ // in order to adapt to cnpm
          // },
          lodash: {
            name: 'chunk-lodash', // split lodash into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?lodash(.*)/ // in order to adapt to cnpm
          },
          vantUI: {
            name: 'chunk-vantUI', // split vantUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?vant(.*)/ // in order to adapt to cnpm
          },
          // vue: {
          //   name: 'chunk-vue', // split vue into a single package
          //   priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          //   test: /[\\/]node_modules[\\/]_?@vue(.*)/ // in order to adapt to cnpm
          // },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
      config.optimization.runtimeChunk('single')
      config.optimization.minimize(true)
      // 配置删除 console.log
      config.optimization.minimizer('terser').tap(args => {
        // remove debugger
        args[0].terserOptions.compress.drop_debugger = true
        // 移除 console.log
        if (process.env.VUE_APP_BUILD_DROP_CONSOLE == 'true') {
          args[0].terserOptions.compress.pure_funcs = ['console.log']
        }
        // 去掉注释 如果需要看chunk-vendors公共部分插件,可以注释掉就可以看到注释了
        args[0].terserOptions.output = {
          comments: false
        }
        return args
      })
    })
  }

以上就是我从webpack3升级webpack4遇到的问题,大家又遇到其他什么问题么,有的话评论区来!!!

相关推荐
GISer_Jing6 小时前
编译原理AST&以Babel为例进行解读、Webpack中自定义loader与plugin
前端·webpack·node.js
GISer_Jing6 小时前
Webpack中Compiler详解以及自定义loader和plugin详解
前端·webpack·node.js
cdcdhj1 天前
vue用通过npm的webpack打包编译,这样更适合灵活配置的项目
vue.js·webpack·npm
augenstern4162 天前
webpack重构优化
前端·webpack·重构
Dontla3 天前
何时需要import css文件?怎么知道需要导入哪些css文件?为什么webpack不提示CSS导入?(导入css导入规则、css导入规范)
前端·css·webpack
积极向上的龙3 天前
首屏优化,webpack插件用于给html中js自动添加异步加载属性
javascript·webpack·html
Attacking-Coder3 天前
前端面试宝典---webpack面试题
前端·面试·webpack
水煮白菜王3 天前
深入理解 Webpack 核心机制与编译流程
前端·webpack·node.js
大G哥3 天前
项目中利用webpack的require.context实现批量引入/导入图片
前端·webpack·node.js
巴巴_羊4 天前
webpack和vite区别
前端·webpack·node.js