webpack版本问题造成项目启动失败

问题背景:

在项目里使用了express库做前端的服务器,结果一运行给我报了23个errors(悲) 

ERROR in ./node_modules/serve-static/index.js 19:14-37
Module not found: Error: Can't resolve 'path' in 'D:\project\vue2\vue-permission-demo\node_modules\serve-static'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "path": false }
 @ ./node_modules/express/lib/express.js 81:0-40
 @ ./node_modules/express/index.js 11:0-41
 @ ./src/utils/http.js 8:0-35 66:29-37
 @ ./src/api/index.js 1:0-34 10:9-18
 @ ./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/@vue/vue-loader-v15/lib/index.js??vue-loader-options!./src/pages/login/index.vue?vue&type=script&lang=js& 1:0-34 12:23-28
 @ ./src/pages/login/index.vue?vue&type=script&lang=js& 1:0-205 1:221-224 1:226-428 1:226-428
 @ ./src/pages/login/index.vue 2:0-57 3:0-52 3:0-52 10:2-8     
 @ ./src/router/index.js 3:0-35 14:13-18
 @ ./src/main.js 4:0-30 9:2-8

webpack compiled with 23 errors

问题定位

可以发现这23个错大部分都是“Module not found”,经查询后发现在webpack5中移除了nodejs核心模块的polyfill自动引入,那么就会造成包的缺失。

解决方法

1、运行下面这行指令安装在 Webpack 中 Polyfill Node.js 核心模块。

npm install node-polyfill-webpack-plugin

 2、在vue.config.json中进行对webpack的配置

//头部引用
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
 
//加入
configureWebpack: { 
    plugins: [new NodePolyfillPlugin()]
}

3、在vue.config.json中手动添加(如果第2步做完后还有报错的话)

即说白了就是在externals中手动引入缺的模块

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");

module.exports = {
  //调整内部的 webpack 配置
  configureWebpack: {
    plugins: [new NodePolyfillPlugin()],
    externals: {
      fs: require('fs'),
      net: require('net'),
      async_hooks: require('async_hooks')
    }
  },
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3300',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值