使用 webpack 编译 typescript 项目

Compiling a typescript project with webpack

我有一个问题要问你 - 如何在保留文件夹和文档树的同时实现多文件编译,同时不以这种方式将每个文件写入 entry

entry: {
    index:'./src/index.ts',
    'bot/main':'./src/bot/main.ts'
  }

但同时,这些文件有它们的名称和位置,就像在 js 中编译之前一样,只是它们不是在 src 文件夹中,而是在 dist 文件夹中?

我目前的配置webpack.config.js

const path = require('path')
const nodeExternals = require('webpack-node-externals')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
  context: __dirname,
  entry: {
    index:'./src/index.ts',
    'bot/main':'./src/bot/main.ts'
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /.ts$/,
        use: {
          loader: 'ts-loader'
        }
      }
    ]
  },
  node: {
    __dirname: false
  },
  resolve: {
    extensions: ['.ts', '.js'],
    plugins: [
      new TsconfigPathsPlugin({
        baseUrl: './src'
      })
    ]
  },
  output: {
    filename: '[name]js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/dist/'
  },
  target: 'node'
}

并且在 production 模式下构建时,所有这些都被编译到一个文件中,同时考虑了所有 URL、导入等

有可能吗?

Webpack 本身不会为您做这些。您将需要编写 litter helper 函数来实现此目的。基本思路是爬取目录,找到所有文件,然后提供给Webpack:

const path = require('path');
const glob = require('glob');


const extension = 'ts';

// Recursively find all the `.ts` files inside src folder.
const matchedFiles = glob.sync(`./src/**/*.${extension}`, {
  nodir: true
});

const entry = {};

matchedFiles.forEach((file) => {

  const SRC_FOLDER = path.join(__dirname, 'src');
  const ABS_PATH = path.join(__dirname, file);

  // Generates relative file paths like `src/test/file.ts`
  const relativeFile = path.relative(SRC_FOLDER, ABS_PATH);
  
  // fileKey is relative filename without extension.
  // E.g. `src/test/file.ts` becomes `src/test/file`
  const fileKey = path.join(path.dirname(relativeFile), path.basename(relativeFile, extension));

  entry[fileKey] = relativeFile;
});


module.exports = {
  context: __dirname,

  // Use the entry object generated above.
  entry,
  // ... rest of the configuration
};