【问题标题】:Using html-webpack-plugin to generate an index.html file in Webpack (project using vue-simple boilerplate)在 Webpack 中使用 html-webpack-plugin 生成 index.html 文件(项目使用 vue-simple 样板)
【发布时间】:2023-09-17 17:49:01
【问题描述】:

每次在 Webpack 中构建应用程序时,我都会尝试生成自己的 index.html 文件,为此,我安装了 html-webpack-plugin

我知道为了在我的 dist 文件夹中生成一个 index.html 文件,我需要在我的 webpack.config.js 文件中包含以下内容:

output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].js',
},
plugins: [
    new HtmlWebpackPlugin(), // creates an index.html file
],

通过上述设置,它应该会生成以下内容,这是我想要的输出:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
  <script type="text/javascript" src="build.js"></script></body>
</html>

不幸的是,我一直在使用vue-simple Webpack boilerplate 来构建我的 VueJS 学习项目,因此,它在输出部分中有一个 publicPath 条目:

output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: '[name].js',
}

通过上述设置,html-webpack-plugin 可以理解地在我的 dist 文件夹中的 index.html 文件中生成以下脚本标记,这不是我需要的,因为 src 现在指向“/dist/build.js” .

<script type="text/javascript" src="/dist/build.js"></script></body>

如果我从我的输出设置中删除 publicPath,我将无法从我的开发服务器加载我的页面,因为一切都会中断。我读了这个SO post about publicPath,但我仍然不确定我应该做什么来实现我的目标,因为一切都是由样板设置的。我应该如何编辑我的 webpack.config.js 文件以便在我构建时生成我想要的 index.html 文件而不破坏我的开发服务器上的任何东西?

以下是我的完整 webpack.config 设置:

const path = require('path');
const webpack = require('webpack');
require("babel-polyfill"); // for async await
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    // babel-polyfill for async await
    // entry: ["babel-polyfill", "./src/main.js"],
    entry: {
        build: ["babel-polyfill", "./src/main.js"]
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: '[name].js', // this will output as build.js
    },
    module: {
        rules: [{
            test: /\.css$/,
            use: [
                'vue-style-loader',
                'css-loader'
            ],
        }, {
            test: /\.scss$/,
            use: [
                'vue-style-loader',
                'css-loader',
                'sass-loader'
            ],
        }, {
            test: /\.sass$/,
            use: [
                'vue-style-loader',
                'css-loader',
                'sass-loader?indentedSyntax'
            ],
        }, {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
                    // the "scss" and "sass" values for the lang attribute to the right configs here.
                    // other preprocessors should work out of the box, no loader config like this necessary.
                    'scss': [
                        'vue-style-loader',
                        'css-loader',
                        'sass-loader'
                    ],
                    'sass': [
                        'vue-style-loader',
                        'css-loader',
                        'sass-loader?indentedSyntax'
                    ]
                }
                // other vue-loader options go here
            }
        }, {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
        }, {
            test: /\.(png|jpg|gif|svg)$/,
            loader: 'file-loader',
            include: '/src/assets/images',
            options: {
                name: '[name].[ext]?[hash]'
            }
        }]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
    },
    devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true
    },
    performance: {
        hints: false
    },
    plugins: [
        new webpack.ProvidePlugin({ // this injects the following into .vue files
            _: "lodash",
            math: "mathjs",
            moment: "moment",
            axios: "axios",
            Chart: "chart.js",
            firebase: "firebase",
        }),
        new HtmlWebpackPlugin(), // creates an index.html file in dist
    ],
    devtool: '#eval-source-map'
};

if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map'
    // http://vue-loader.vuejs.org/en/workflow/production.html
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        }),
        new webpack.LoaderOptionsPlugin({
            minimize: true
        })
    ]);
}

下面是我的文件夹结构:

【问题讨论】:

    标签: javascript webpack vue.js html-webpack-plugin


    【解决方案1】:

    您也可以使用 vue-cli 来搭建脚手架。 (在此处阅读 vue-cli 的 vue 文档https://vuejs.org/2015/12/28/vue-cli/

    以下将为您提供完整的预配置 webpack 配置:

    vue init webpack project-name

    然后您可以使用npm run buildyarn build,这将在“dist”文件夹中生成您的 index.html。

    【讨论】:

    • 感谢您的建议!我意识到这是一种可能性,但我认为迁移我所做的一切并冒着破坏很多东西的风险可能会有点痛苦......你知道我如何在 vue-simple 脚手架中解决我的问题吗还是您认为我应该将所有内容都移到标准的 vue Webpack 模板中?
    • 我建议迁移。但是,以下内容应该可以解决您的问题 -> 输出:{ path: path.resolve(__dirname, './dist'), publicPath: '', filename: '[name].js', // 这将输出为 build .js }