【问题标题】:Compiling a typescript project with webpack使用 webpack 编译 typescript 项目
【发布时间】:2022-02-02 16:19:51
【问题描述】:

我有一个问题要问你——如何在保留文件夹和文档树的同时实现多文件编译,而不是以这种方式将每个文件写入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、导入等。

有可能吗?

【问题讨论】:

    标签: javascript node.js typescript webpack compilation


    【解决方案1】:

    Webpack 本身不会为你做这些。您将需要编写垃圾辅助函数来实现这一点。基本思路是爬取目录,找到所有文件,然后提供给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
    };
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 2017-12-21
      • 2020-10-11
      • 2016-03-02
      • 2018-03-12
      • 2020-09-13
      • 2017-07-25
      • 2016-12-08
      • 2020-06-15
      相关资源
      最近更新 更多