首页 > 解决方案 > babel-loader 破坏了 npm 包中的 `this` 变量

问题描述

我从awesome-typescript-loaderto切换到,babel-loader并且在我们使用的 npm 包中遇到了这个问题 - lodash-inflection

Uncaught TypeError: this.pluralize is not a function at pluralize (lodash-inflection.js:68)

下面是损坏的()和工作的()之间的断点。

在此处输入图像描述

中的 this变量lodash-inflection.js变成了window而不是包所期望的实际值,因此包不再工作。

下面是修改的内容webpack.js

老的

{
  test: /\.tsx?$/,
  exclude: /(node_modules|bower_components)/,
  loader: 'awesome-typescript-loader',
  options: {
    getCustomTransformers: isDev && path.join(__dirname, './webpack.ts-transformers.js')
  }
}

新的

{
  test: /\.tsx?$/,
  exclude: /(node_modules|bower_components)/,
  use: [{
    loader: 'babel-loader',
    options: {
      presets: [
        ["@babel/preset-env", { modules: "false" }],
        ["@babel/preset-typescript", { "allExtensions": true, "isTSX": true }],
        "@babel/preset-react",
      ],
      plugins: [
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-object-rest-spread",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-runtime",
        "@babel/plugin-proposal-optional-chaining",
        "@babel/plugin-proposal-nullish-coalescing-operator"
      ],
      env: {
        development: {
          plugins: [
            [
              "styled-components",
              {
                displayName: true
              }
            ]
          ]
        }, production: {
          plugins: [
            [
              "styled-components",
              {
                displayName: false
              }
            ]
          ]
        }
      }
    }
  }],
}

我见过的大多数 babel 选项都是这样的。我还尝试更改presets.

标签: javascriptreactjstypescriptwebpack

解决方案


查看包,尝试导入和使用单个方法lodash-inflection似乎存在一个未解决的问题。尝试导入整个包:

import inflection from 'lodash-inflection';
//...
inflection.pluralize(foo, bar);

推荐阅读