Webpack 5报Can't resolve 'crypto'等Node核心模块错误的解决方案
Webpack 5 前端项目
Module not found: Error: Can't resolve 'crypto' 错误解决方案 运行基于Webpack 5的前端项目时,控制台会抛出上述错误,官方变更说明如下:
重大变更:webpack < 5 版本默认内置Node.js核心模块的polyfill,webpack 5及以上版本不再支持该默认配置,请确认是否需要使用对应模块,并为其配置polyfill。
提示:该类报错不仅会出现在crypto模块上,http、https、os等其他Node.js核心模块也可能触发同类问题,均可参照以下逻辑适配。
安装所需polyfill包
本案例需用到crypto-browserify包,先检查项目node_modules目录下是否存在对应文件夹,不存在则执行安装命令:npm install crypto-browserify若需要指定Node版本对应的类型依赖,可额外执行:
yarn add @types/node@15.12.5 -D安装完成后,打开
node_modules/crypto-browserify目录下的package.json文件,在devDependencies配置项后添加如下内容:, "optionalDependencies": {}, "browser": { "crypto": false }注:需添加在devDependencies配置之后
配置tsconfig.json路径映射
打开项目根目录的tsconfig.json文件,在compilerOptions配置中添加如下paths配置:"compilerOptions": { "paths":{ "crypto": ["node_modules/crypto-browserify"], "http": ["node_modules/stream-http"], "https": ["node_modules/https-browserify"] } }Angular项目额外配置
若使用Angular框架,需额外打开项目根目录的angular.json文件,添加如下配置:"architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "allowedCommonJsDependencies": ["crypto"], "allowedCommonJsDependencies": ["http"], "allowedCommonJsDependencies": ["https"] } } }
内容的提问来源于stack exchange,提问作者Alexander Wolters
相关产品推荐
相关产品推荐

