摘要
记录一次webapck5踩坑:
Module not found: Error: Can't resolve 'xxx' in ...
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
版本
- node:v16.20.2
- npm: 8.19.4
- yarn: 1.22.19
问题
使用create-react-app创建程序,模板选择typescript. 用craco改写webpack配置。 启动程序报错:
Module not found: Error: Can't resolve 'crypto' in 'E:\studyspace\React\react-ts-main\node_modules\jsonwebtoken'
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: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
- If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }
这个错简单说就是,有一个模块没有找到。
在webpack5之前的版本会默认包含node的核心模块。
webpack5不再支持了,你要用的话需要自己去配置。
解决方案
每次报错都要单独配置一次显然是很繁琐的,已经有大神写了专门的插件用来解决这个问题。 node-polyfill-webpack-plugin
安装
yarn add node-polyfill-webpack-plugin -D
配置
在craco.config.ts
const path = require('path')
// 插件
const { ProvidePlugin, EnvironmentPlugin } = require('webpack')
const CracoLessPlugin = require('craco-less')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const webpackConfig = {
webpack: {
// 别名
alias: {
'@': path.resolve(__dirname, 'src')
},
plugins: [
new EnvironmentPlugin(['NODE_ENV', 'DEBUG']),
new NodePolyfillPlugin(),
new ProvidePlugin({
process: 'process/browser'
})
]
},
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: {
'@primary-color': '#FFBE98'
},
javascriptEnabled: true
}
}
}
}
],
babel: {
plugins: [
[
// 支持装饰器语法
'@babel/plugin-proposal-decorators',
{
legacy: true
}
]
]
},
resolve: {
alias: {
process: 'process/browser',
},
}
}
export default webpackConfig
补充
我的程序process一直报未定义,我使用了webpack的插件EnvironmentPlugin。
new EnvironmentPlugin(['NODE_ENV', 'DEBUG'])
NODE_ENV和DEBUG需要在根目录增加 .env 文件,并在文件中声明。
GENERATE_SOURCEMAP=false
NODE_ENV='dev'
DEBUG=false
初来乍到,欢迎大佬指点