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

相关推荐
Moment20 小时前
拆包的艺术:Webpack SplitChunksPlugin 执行流程全流程揭秘 🤩🤩🤩
前端·javascript·webpack
Huanzhi_Lin2 天前
webpack配置导致浏览器自动刷新
前端·javascript·webpack
原生高钙2 天前
万字webpack精华总结:那些面试官提问的实现原理你答上来了吗
前端·webpack
ak啊3 天前
Webpack热更新模块-HMR
前端·webpack·源码
ak啊4 天前
Webpack 插件开发模式
前端·webpack·源码
Moment4 天前
一图看懂 Webpack HMR 原理 🤔🤔🤔
前端·javascript·webpack
ak啊5 天前
插件与 Hook 的交互-Webpack 插件系统深度解析
webpack·源码
一梦南柯5 天前
无需CI/CD!手把手教你用Webpack插件实现Vue项目一键标准化打包
前端·vue.js·webpack
kovlistudio5 天前
红宝书第三十二讲:零基础学会模块打包器:Webpack、Parcel、Rollup
前端·javascript·webpack·node.js
霸王蟹5 天前
Webpack中loader的作用。
前端·javascript·vue.js·笔记·webpack·node.js