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

SPFX中使用babel-loader遇TypeError: this.getOptions is not a function错误

解决SharePoint WebPart中babel-loader@9.1的this.getOptions is not a function错误

问题背景

我要创建SharePoint WebPart,使用docx npm模块生成文档,因加载器相关问题添加了webpack配置并引入babel-loader@9.1,但执行gulp bundle命令时出现错误。

错误信息

Error - [webpack] 'dist':
./lib/webparts/docxWebpart/DocxWebpartWebPart.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: this.getOptions is not a function
at Object.loader (D:/Practice/DocxCreatorPOC/DocxReactPOC/node_modules/babel-loader/lib/index.js:44:28)
at Object. (D:/Practice/DocxCreatorPOC/DocxReactPOC/node_modules/babel-loader/lib/index.js:39:12)

环境信息

  • babel-loader: 9.1
  • Node: 16.20.1
  • NPM: 9.8.1
  • OS: Windows 10

当前gulpfile.js中的webpack配置

build.configureWebpack.mergeConfig({
  additionalConfiguration: (generatedConfiguration) => {
    generatedConfiguration.module.rules.push(
      {
        test: /\.(?:js|mjs|cjs)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', { targets: "defaults" }]
            ]
          }
        }
      }
    );

    return generatedConfiguration;
  }
});
build.initialize(require('gulp'));

解决方案

这个错误的核心原因是babel-loader@9.x仅支持webpack 5,但你的SharePoint SPFx项目(基于Node 16)使用的是webpack 4,this.getOptions是webpack 5的专属API,webpack 4中不存在该方法,所以触发报错。

解决步骤如下:

  1. 卸载当前不兼容的babel-loader版本:
npm uninstall babel-loader
  1. 安装兼容webpack 4的babel-loader@8.x版本(推荐8.3.0,兼容性稳定):
npm install babel-loader@8.3.0 --save-dev
  1. 同步升级/降级babel核心依赖,确保版本匹配:
npm install @babel/core@7.22.0 --save-dev
npm install @babel/preset-env@7.22.0 --save-dev
  1. 重新执行gulp bundle命令,验证错误是否修复。

注意:不要尝试强行升级SPFx项目的webpack到5,这会引发大量其他依赖兼容性问题,降级babel-loader到适配版本是最稳妥的方案。

内容的提问来源于stack exchange,提问作者Vaibhav Chauhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:52:09