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 stylus-loader@3.0.2 --save-dev

问题3

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

解决方法

这个就是目前版本的webpack-dev-server@2.11.5 不支持 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 
会下载到+ extract-text-webpack-plugin@4.0.0-beta.0 

注意修改如下配置

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)

解决方法

安装vue-loader@14.2.2即可
npm install vue-loader@14.2.2

问题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遇到的问题,大家又遇到其他什么问题么,有的话评论区来!!!

相关推荐
一大树2 天前
Webpack 配置与优化全攻略:从基础到进阶实战
webpack
布兰妮甜3 天前
Vite 为什么比 Webpack 快?原理深度分析
前端·webpack·node.js·vite
一枚前端小能手5 天前
🚀 Webpack构建等到怀疑人生?试试这几个优化
前端·webpack
拾光拾趣录5 天前
模块联邦(Module Federation)微前端方案
前端·webpack
萌萌哒草头将军5 天前
🚀🚀🚀 Webpack 项目也可以引入大模型问答了!感谢 Rsdoctor 1.2 !
前端·javascript·webpack
最爱吃南瓜7 天前
JS逆向实战案例之----【通姆】252个webpack模块自吐
开发语言·javascript·爬虫·webpack·js逆向·算法模拟
爱敲代码的小旗7 天前
Webpack 5 高性能配置方案
前端·webpack·node.js
桃桃乌龙_95278 天前
受不了了,webpack3.x升级到webpack4.x
前端·webpack
前端缘梦8 天前
深入理解Webpack配置:入口与出口的细节解析
前端·webpack·前端工程化
yuanmenglxb20049 天前
解锁webpack核心技能(二):配置文件和devtool配置指南
前端·webpack·前端工程化