You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Webpack将单文件夹文件按文件夹打包并保留目录结构?

Webpack按目录打包并保留原结构的配置问题

项目结构

src
|-- project one
|-- project two

预期效果

执行npm run build后,Webpack需将project one下所有文件打包为一个产物,project two同理,最终dist目录保留原结构:

dist
|-- project one
|   |-- [打包后的文件].js
|-- project two
|   |-- [打包后的文件].js

当前Webpack配置

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

const entryFiles = glob
.sync("./src/**/*.ts")
.reduce((previousValue, currentValue, currentIndex, array) => {
    return typeof previousValue === "string"
    ? {
        [path.basename(previousValue, path.extname(previousValue))]:
            previousValue,
        [path.basename(currentValue, path.extname(currentValue))]:
            currentValue,
        }
    : {
        ...previousValue,
        [path.basename(currentValue, path.extname(currentValue))]:
            currentValue,
        };
});

module.exports = {
    entry: entryFiles,
    resolve: {
        extensions: [".ts"],
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].js",
    },
    module: {
        rules: [
        {
            test: /^(?!.*\.spec\.ts$).*\.ts$/,
            loader: "ts-loader",
            exclude: /node_modules/,
        },
        ],
    },
};

问题描述

当前配置无法实现预期需求:既不能按文件夹维度打包,也无法在dist目录中保留原有的目录结构。


内容的提问来源于stack exchange,提问作者r3plica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:45:10