使用Webpack 4和它的HtmlWebpackPlugin和html-loader一起,我试图:
但是,当 webpack.config.js 中存在html-loader时,这不起作用。
如果我可以使用首选的相同语法,但我已尝试使用${ }
作为标题标记,但我收到了构建错误htmlWebpackPlugin undefined
。
<!doctype html>
<html>
<head>
<title><%= htmlWebpackPlugin.options.title %></title> <!-- this doesn't work -->
<!-- <title>${htmlWebpackPlugin.options.title}</title> //also doesn't work -->
</head>
<body>
<section>${require("./path/to/other.html")}</section> <!-- this works fine -->
</body>
</html>
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './src/main.js',
devServer: {
contentBase: './src',
port: 4200,
open: true
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: './src/index.html'},
title: 'Index Page')
],
module: {
rules: [
{
test: /\.jsx?$/,
include: /src/,
exclude: /node_modules/
},
{
test: /\.(html)$/,
exclude: /node_modules/,
use: {
loader: 'html-loader',
options: {
attrs:[':data-src'],
minimize: false,
conservativeCollapse: false,
interpolate: true
}
}
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}
]
}
]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
答案 0 :(得分:1)
可以通过按以下顺序堆叠以下装载程序来实现:
{
test: /\.html$/,
use: [{
loader: 'ejs-loader'
}, {
loader: 'extract-loader'
}, {
loader: 'html-loader',
options: {
interpolate: true
}
}
html-loader
首先替换内插片段,然后我们需要提取结果HTML-这就是为什么我们使用extract-loader
然后ejs-loader
然后可以替换ejs
片段及其原因确实看到了htmlWebpackPlugin
变量。
答案 1 :(得分:0)
添加interpolate = required对我有用,这限制了html-loader,因此它只能解析require语句,而不是变量。
{
test: /\.(html)$/,
use: {
loader: 'html-loader?interpolate=require'
}
},
答案 2 :(得分:0)
今天刚遇到此问题,找到了解决方案,并且此页面仍在我的浏览器中打开。
解决此问题的另一种方法是将模板文件重命名为.ejs
,因此将index.html
重命名为index.html.ejs
。
然后配置文件应该是:
plugins: [
new HtmlWebpackPlugin(
{
hash: true,
template: './src/index.html.ejs' // rename the file accordingly
},
title: 'Index Page')
],
这样html-webpack-plugin将首先处理ejs,因为它实际上是ejs的后备加载程序。并且html-loader将在html-webpack-plugin产生html之后运行。
答案 3 :(得分:0)
您的代码在错误的位置有一个大括号。
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: './src/index.html'},
title: 'Index Page')
],
尝试这样做:
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: './src/index.html',
title: 'Index Page'
})
],