You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:52:11