Webpack-dev-server 不使用 HtmlWebpackPlugin 选项中的模板

我确定我错过了一些简单的东西,但我看不到它......


我正在使用一个 HtmlWebPlugin 实例,每个页面/入口点都有一个模板。当我使用 webpack-dev-server 只有第一个实例实际上尊重模板中的内容时,其余的只使用简单的 html 和 meta 标签


将文件写入磁盘,无论是通过将 WriteFilePlugin 与开发服务器一起使用,还是通过简单地在没有开发服务器的情况下构建文件,都可以正确使用模板。我很难过。


预期: about.html/index.html 这是我使用 write-file-webpack-plugin 和运行'webpack --config webpack.config.js'. Index.html 是相同的。


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>About</title>

</head>

<body>

    <p>About</p>

</body>

</html>

Webpack-dev-server 的实际输出:(查看页面源代码)


<!DOCTYPE html>

<html>

    <head>

        <meta charset="utf-8"/>

    </head>

    <body>

        <script type="text/javascript" charset="utf-8" src="/about.js"></script>

    </body>


</html>

配置:


webpack.config.js


const HtmlWebpackPlugin = require('html-webpack-plugin');

const WriteFilePlugin = require('write-file-webpack-plugin');

const path = require('path');


module.exports = {

    entry: {

        index: './src/js/index.js',

        about: './src/js/about.js'

    },

    output: {

        path: path.resolve(__dirname, 'dist'),

        filename: '[name].js'

    },

    module: {

        rules: [

            {

                test: /\.css$/,

                use: ['style-loader', 'css-loader']

            },

            {

                test: /\.html$/,

                use: 'html-loader'

            }

        ]

    },

    devServer: {

        openPage: 'about'

    },

    plugins: [

        new WriteFilePlugin(),

        new HtmlWebpackPlugin({

            filename: 'index.html',

            template: 'src/index.ejs',

            chunks: ['index']

        }),

        new HtmlWebpackPlugin({

            filename: 'about.html',

            template: 'src/about.ejs',

            chunks: ['about']

        }),

    ]

};

我看不出有什么明显的错误,但是我是多页面和 webpack 的新手


小怪兽爱吃肉
浏览 136回答 3
3回答

千万里不及你

好吧,我不妨把我的耻辱作为答案,以防它在未来帮助其他人......我导航到localhost:8080/about而不是localhost:8080/about.html。脚本是在 /about 处注入的,但模板不是。在 /about.html 中使用了脚本和模板。我不确定为什么会有差异,但那是我的问题!

阿波罗的战车

我认为你在那里缺少一个加载程序检查https://www.npmjs.com/package/ejs-webpack-loader我在带有 HtmlWebpackPlugin 的包页面中找到了一个示例,尝试一下也许它会对您有所帮助plugin: {&nbsp; new HtmlWebpackPlugin({&nbsp; &nbsp; template: '!!ejs-webpack-loader!src/index.ejs'&nbsp; })}

30秒到达战场

作为参考: https: //github.com/jaketrent/html-webpack-template/issues/69#issuecomment-376872044。简而言之,您需要对所有块进行循环以插入到最终的 html 文件中。以下是模板文件中的示例代码<% for (var chunk in htmlWebpackPlugin.files.js) { %>&nbsp; &nbsp; <script src="<%= htmlWebpackPlugin.files.js[chunk]%>"></script><% } %>希望对您有所帮助,如有误会请谅解。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript