babel-loader在npm包中破坏了`this`变量

时间:2019-12-04 08:57:33

标签: javascript reactjs typescript webpack

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

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

以下是断点()和工作点()之间的断点。

enter image description here

this中的lodash-inflection.js变量将变成window,而不是软件包所期望的实际值,因此该软件包不再起作用。

下面是对webpack.js

的更改

OLD

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

NEW

{
  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
              }
            ]
          ]
        }
      }
    }
  }],
}

我所见过的大多数通货膨胀选择就是这样。我还尝试过更改presets的顺序。

1 个答案:

答案 0 :(得分:0)

看着lodash-inflection包,似乎有open issue试图导入和使用单个方法。尝试导入整个程序包:

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