【问题标题】:ts + webpack bundling for node cannot find module 'path'ts + webpack 捆绑节点找不到模块“路径”
【发布时间】:2021-11-16 02:24:50
【问题描述】:

我知道以前有人问过这个问题,但我无法得到任何可接受的工作答案。

我的目标是将我的每个入口点捆绑为单个 [entry].js 以实现可移植性。理想情况下,我希望有 [entry].js 和 [entry].[modules/vendor].js 但不是必需的。

我尝试过的:

  • webpack-node-externalsallowlist 一起使用。导致找不到深层模块
  • 手动外部选项path: "commonjs path"。不改变结果
  • const {} = require('path') 而不是 import {} from 'path'。也不会改变任何东西
  • 我认为下面的配置得到了最接近的结果,只是它找不到内置插件。

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "outDir": "launch",
    "noImplicitAny": false,
    "target": "es5",
    "allowJs": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
  },
  "exclude": [
    "__tests__",
    "dist",
    "launch"
  ],
  "include": [
    "src/Auth",
    "src/Gate",
    "src/Patch",
    "src/Account",
    "src/Proxy",
  ]
}

webpack.config.js

const path = require('path');
module.exports = {
  target: 'node',
  mode: 'production',
  entry: {
    'gate': './src/Gate/index.ts',
    'patch': './src/Patch/index.ts',
    'auth': './src/Auth/index.ts',
    'account': './src/Account/index.ts',
    'proxy': './src/Proxy/index.ts',
  },
  stats: {warnings:false},
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  optimization: {
    usedExports: true,
    chunkIds: 'natural',
    splitChunks: {
      // default splitChunks config
      chunks: 'async',
      minSize: 20000,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      enforceSizeThreshold: 50000,
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    }
  }
};

【问题讨论】:

  • 通常情况下,当为 Node 环境打包时,我们根本不应该定义供应商块,因为它运行 node_modules 应该总是在那里使用。

标签: node.js typescript webpack node-modules bundler


【解决方案1】:

我发现了问题,是包cli 有自己的托管模块解析类型,它与webpack 中断。我已将其替换为 commander

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2021-02-13
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多