使用webpack保留输出目录中的文件夹结构

11

我有如下文件夹结构:

/index.html
/app/index.tsx

使用webpack打包后,我希望将bundle.js注入index.html并输出到以下目录:

/dist/index.html
/dist/app/bundle.js
/dist/app/bundle.js.map

我有以下的webpack配置:
var webpack = require("webpack")
var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = [
    {
        entry: "./app/index",
        output: {
            path: "./dist/app",
            filename: "bundle.js"
        },
        devtool: "source-map",
        resolve: {
            extensions: ["", ".tsx", ".ts", ".js"]
        },
        plugins: [
            new webpack.optimize.UglifyJsPlugin(),
            new HtmlWebpackPlugin({
                "filename": "./index.html",
                "template": "html!./index.html"
            })
        ],
        module: {
            loaders: [
            { test: /\.tsx?$/, loader: "ts-loader" },
            ]
        }
    }, 
    {
        output: {
            path: "./dist",
            filename: "bundle.js"
        },
        plugins: [
            new HtmlWebpackPlugin({
                "filename": "./index.html",
                "template": "html!./index.html"
            })
        ]    
    }
]

看起来工作得很好,但是脚本bundle.js并没有像预期的那样注入到index.html中。HtmlWebpackPlugin应该会做到这一点。我做错了什么?


你的 ./index.html 文件中是否包含了 HtmlWebpackPlugin 所期望的模板?如果没有,它将不会写入脚本部分。 - Juho Vepsäläinen
是的。我可以重新编写配置文件,使脚本注入成功,但文件夹结构将不会保留。 - Chad
如果您没有使用webpack-dev-server,您可以在此处找到答案:http://stackoverflow.com/questions/36106276/how-to-separate-index-html-and-assets-in-webpack-dev-server/36106310?noredirect=1 - Bob Sponge
2个回答

2

这正是我想要的。我不知道如何表达问题。谢谢! - Chad

0

Webpack的HTML Bundler插件可以读取源目录中的模板文件,并将编译后的HTML文件以相同的结构保存在输出目录中。

例如,在src/views/源目录中有一些模板:

src/views/index.html
src/views/about/index.html
src/views/news/sport/index.html
src/views/news/sport/hockey/index.html
src/views/news/sport/football/index.html
...

我们希望在dist/目录中拥有相同的文件夹结构:
dist/index.html
dist/about/index.html
dist/news/sport/index.html
dist/news/sport/hockey/index.html
dist/news/sport/football/index.html
...

只需安装html-bundler-webpack-plugin即可。
npm install html-bundler-webpack-plugin --save-dev

在Webpack配置中添加插件:

const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlBundlerPlugin({
      entry: 'src/views/', // the template directory
    }),
  ],
};

所有位于 src/views/ 目录下的模板将会被编译并保存在具有相同结构的 dist/ 目录中。 HTML 中引用的所有源脚本和样式文件将会自动处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接