您需要确保图像由 WebPack 处理,因此它们存在匹配的加载器(例如文件加载器 https://github.com/webpack/file-loader).
为此,您必须明确要求相应属性中的文件。为了能够显式地请求index.html中的文件,您必须依次为index.html使用加载器itself,允许内联处理 JS。
这实际上取决于您的设置(即您是否设置了 html-webpack-loader);看看FAQ https://github.com/ampedandwired/html-webpack-plugin/blob/master/docs/template-option.md,解释基础知识。
所以假设,你有一些这样的情况:
// webpack config.js 中的某个位置
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'head',
}) //..
]
You can require in你的index.html图像是这样的:
<link rel="apple-touch-icon" sizes="120x120" href="${require('./favicons/apple-touch-icon-120x120.png')}">
这将尝试加载苹果触摸图标-120x120.png通过 WebPack,所以你必须确保有一个加载器andhtml-loader 还需要配置:
//somewhere in your webpack.config.js
module: {
loaders: [
{
test: /\.png$/,
loader: 'file?name=assets/icons/[name].[hash].[ext]'
},
{
test: /\.html$/,
loader: 'html',
query: {
interpolate: 'require'
}
} //..
] //..
}
您只需对以下图像使用 requirenot inside <img>
- 标签,这些标签将被 html-webpack-loader 自动拾取。
html-loader 的未来版本可能会改变这种行为 ->https://github.com/webpack/html-loader/issues/17 https://github.com/webpack/html-loader/issues/17