Webpack 不处理基于 TypeScript 的 node_modules

Webpack doesn't process TypeScript-based node_modules

关于将 .ts.tsx 文件从 node_modules 文件夹导入到应用程序中,我卡住了一段时间。原来 babel 无法从那里处理基于打字稿的东西。

这是一个例子:

ERROR in ./node_modules/@ui-kit/components/Link/index.tsx 32:1
Module parse failed: Unexpected token (32:1)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|   arrowName = 'down',
|   linkColor
> }: IProps) => {
|   const _handleClick = (e) => {
|     onClick && onClick(e);
 @ ./node_modules/src/index.ts 10:0-37 25:0-44:2

这是我的 TS|TSX 加载程序:

  {
    test: /\.(js|jsx|ts|tsx)?$/,
    exclude: [/node_modules\/(?!(@ui-kit)\/).*/],
    use: [
      {
        loader: 'ts-loader',
        options: {
          allowTsInNodeModules: true,
          compilerOptions: {
            target: __DEV__ ? 'ES2019' : 'ES5'
          }
        }
      }
    ]
  }

让我们打开 environmet.js 文件。然后,删除通用加载程序:

// ------------------------------------
// Loaders
// ------------------------------------
environment.loaders.delete('file')
environment.loaders.delete('babel')
environment.loaders.delete('nodeModules')

通过配置选项添加您自己的:

// ------------------------------------
// Loaders
// ------------------------------------
environment.config.module = {
  ...environment.config.module,
  rules: [
    {
      test: /\.(js|jsx|ts|tsx)?$/,
      exclude: [/node_modules\/(?!(@ui-kit)\/).*/],
      use: [
        {
          loader: 'ts-loader',
          options: {
            allowTsInNodeModules: true,
            compilerOptions: {
              target: 'ES2019'
            }
          }
        }
      ]
    },
    {
      type: 'javascript/auto',
      test: /\.json$/,
      use: ['json-loader']
    },
    // FILE/IMAGES
    {
      test: /\.woff(\?.*)?$/,
      use: ['url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff']
    },
    {
      test: /\.woff2(\?.*)?$/,
      use: ['url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2']
    },
    {
      test: /\.otf(\?.*)?$/,
      use: ['file-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype']
    },
    {
      test: /\.ttf(\?.*)?$/,
      use: ['url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream']
    },
    {
      test: /\.eot(\?.*)?$/,
      use: ['file-loader?prefix=fonts/&name=[path][name].[ext]']
    },
    {
      test: /\.svg(\?.*)?$/,
      use: ['url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml']
    },
    {
      test: /\.(png|jpg)$/,
      use: ['url-loader?limit=8192']
    }
  ]
}