Angular CLI+Webpack5项目配置mammoth库遇process未定义问题求助
Angular CLI + Webpack5 配置Mammoth.js解决"process is not defined"问题
问题根源
Webpack5移除了Node.js核心模块的默认polyfill,而Mammoth内部依赖process对象,浏览器环境中找不到该变量就会抛出报错。
解决步骤
1. 修正custom-webpack.config.js
添加Webpack的DefinePlugin来全局定义process对象:
const webpack = require('webpack'); module.exports = { plugins: [ new webpack.DefinePlugin({ 'process': JSON.stringify({}), 'process.env': JSON.stringify({}) }) ] };
2. 确认angular.json的自定义Webpack配置关联正确
确保build配置使用@angular-builders/custom-webpack:browser构建器,并正确指向你的配置文件:
"build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./custom-webpack.config.js" }, // 保留原有其他配置项 } }
如果未安装@angular-builders/custom-webpack,先执行安装命令:npm install @angular-builders/custom-webpack --save-dev
3. 无需手动创建polyfills.ts
Angular 14及以上版本不再默认生成polyfills.ts文件,手动创建反而容易引发导入错误,直接删除你自行创建的该文件即可,依赖polyfill的问题通过Webpack配置解决。
4. 组件内正确使用Mammoth
在文件上传组件中按以下方式调用,确保仅在浏览器环境处理文件:
import mammoth from 'mammoth'; async handleDocxUpload(event: Event) { const fileInput = event.target as HTMLInputElement; const docxFile = fileInput.files?.[0]; if (!docxFile) return; const buffer = await docxFile.arrayBuffer(); const htmlResult = await mammoth.convertToHtml({arrayBuffer: buffer}); // 将转换后的HTML渲染到页面或做其他处理 this.convertedHtml = htmlResult.value; }
额外排查点
- 清理缓存:执行
npm run build -- --clean或删除node_modules/.cache文件夹 - 检查package.json中Angular CLI与Webpack版本是否兼容,尽量使用官方推荐的配套版本
内容的提问来源于stack exchange,提问作者ScaryPotato123
相关产品推荐
相关产品推荐

