Webpack 捆绑但不解析 node_modules 包中的打字稿

Webpack bundling but not resolving typescript from node_modules package

各位大侠,我已经尝试了所有我能想到的不同方法来解决这个问题。

我们临时有两个文件夹 mono-repo(没有 yarn 工作区)。一种叫做 Mgt-Shared 一种叫做 Server。我们参考了服务器 package.json"mgt-shared": "file:../mgt-shared" 的共享,我 运行 一个简单的 npm install 将我们的共享共享到服务器 node_modules。 这两个项目都是混合打字稿和 javascript。 当我 运行 webpack 尝试捆绑服务器时,它工作正常,来自共享的 Typescript 文件显示在捆绑列表中但是当我 运行 node dist/app.bundle.js - 它无法解决一些模块(特别是所有打字稿的模块)。 当我 运行 webpack --json 我发现这个(看起来它正在正确解析):

    {
      "id": "mgt-shared/discounts/discount_reasons",
      "identifier": "external \"mgt-shared/discounts/discount_reasons\"",
      "name": "external \"mgt-shared/discounts/discount_reasons\"",
      "index": 23,
      "index2": 15,
      "size": 42,
      "built": true,
      "optional": false,
      "prefetched": false,
      "chunks": [
        "main"
      ],
    ...
      "failed": false,
      "errors": 0,
      "warnings": 0,
      "assets": [],
      "reasons": [
        {
          "moduleId": "./src/discounts/discount.ts",
          "moduleIdentifier": "/home/mygastank/WebstormProjects/mygastank/server/node_modules/babel-loader/lib/index.js!/home/mygastank/WebstormProjects/mygastank/server/src/discounts/discount.ts",
          "module": "./src/discounts/discount.ts",
          "moduleName": "./src/discounts/discount.ts",
          "type": "cjs require",
          "userRequest": "mgt-shared/discounts/discount_reasons",
          "loc": "20:24-72"
        },
        {...
      ],
      "providedExports": null,
      "optimizationBailout": [],
      "depth": 6
    },

我的 webpack 配置是这样的:

const nodeExternals = require('webpack-node-externals')
module.exports = {
  mode: 'development',
  target: 'node',
  // This forces resolution of native node modules
  externals: [nodeExternals({ modulesFromFile: true })],
  entry: './src/index',
  output: {
    filename: 'app.bundle.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.json'],
  },
  module: {
    rules: [
      {
      // Include ts, tsx, js, and jsx files.
      test: /\.(ts|js)?$/,
      loader: 'babel-loader',
      include: [/node_modules\/mgt-shared/],
      exclude: [/node_modules/],
      options: {
        presets: [
          [
            'env',
            {
              'targets': {
                'node': 'current'
              }
            }
          ],
          ['@babel/preset-typescript',
            { 'allExtensions': true, 'isTSX': true }]
        ]
      }
    }]
  }
}

我发现有一种方法可以将其他目录列入白名单。

我需要将 whitelist 键添加到 nodeExternals 的选项中,如下所示:

  externals: [nodeExternals({
    whitelist: [/mgt-shared/],
    modulesFromFile: true
  })],

其他一切都能够保持不变。