使webpack包含html文件

时间:2018-07-16 00:11:42

标签: javascript node.js webpack electron

注意:我是webpack的初学者。

我正在尝试使Webpack加载我的.htmls文件(index.html和login.html),因为它们将用作我的电子应用程序的窗口。到目前为止,这是我尝试过的结果,

rules: [
            {
                test: /\.html$/,
                use: ["html-loader"]
            },
...

rules: [
            {
                test: /\.html$/,
                loader: "file-loader"
            },
...

这是我的webpack.config.js文件:

const path = require("path");
const { spawn } = require("child_process");

const srcDir = path.resolve(__dirname, "src/renderer");
const outDir = path.resolve(__dirname, "build/client");

const defaultIncludes = [srcDir];

module.exports = {
    entry: `${srcDir}/index`,

    output: {
        path: outDir,
        filename: "app.bundle.js"
    },

    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json", ".html"]
    },

    module: {
        rules: [
            {
                test: /\.html$/,
                loader: "file-loader"
            },
            {
                // Include ts, tsx, and js files.
                test: /\.(tsx?)|(js)$/,
                exclude: /node_modules/,
                loader: "babel-loader",
                include: defaultIncludes
            },
            {
                test: /\.scss$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    "css-loader", // translates CSS into CommonJS
                    "sass-loader" // compiles Sass to CSS
                ]
            },
            {
                test: /\.(ttf|eot|woff|woff2)$/,
                loader: "file-loader",
                options: {
                    name: "fonts/[name].[ext]"
                }
            }
        ]
    },

    devServer: {
        inline: true,
        contentBase: outDir,
        compress: true,

        stats: {
            colors: true,
            chunks: false,
            children: false
        },

        before() {
            spawn("electron", ["."], {
                shell: true,
                env: process.env,
                stdio: "inherit"
            }).on("close", code => process.exit(0)).on("error", spawnError => console.error(spawnError));
        }
    },

    target: "electron-renderer",
    mode: "development"
};

我在做什么错? Webpack将所有内容构建到/build中,但不包括.html文件(位于我的/src/目录下的index.html和login.html)。

1 个答案:

答案 0 :(得分:2)

HTML文件的加载程序配置将允许对HTML文件的require调用在javascript文件中起作用。使用文件加载器,您将获得文件路径,使用HTML加载器,您将获得调用后的HTML内容。

如果您希望将HTML文件与已编译的源代码一起复制,则必须使用copy-webpack-pluginhtml-webpack-plugin之类的插件。