我正在配置imagemin-webp-webpack-plugin以将我的所有 .png 和 .jpg 图像转换src/assets/images
为dist/assets/images
. 当我运行构建命令时,转换成功。所有图像都已转换为 webp 并分发到dist/assets/images
. 我认为“这很简单”,是时候<picture>
在我的文件中创建标签src/index.html
以开始引用 .webp 图像了:
src/index.html:
<picture>
<source srcset="assets/images/img-hero-home-attorney.webp" type="image/webp">
...
...
</picture>
当我npm run build
再次,这次我得到:
ERROR in ./src/index.html (./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html)
Module not found: Error: Can't resolve './assets/images/img-hero-home-attorney.webp' in '/Users/**/**/**/**/**/**/src'
@ ./src/index.html (./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html) 6:33-87
这对我来说很有意义。这些图像不存在,src/assets/images/
因此 Webpack 无法解决这些问题。
src/index.html
所以现在我遇到了一个障碍:当这些图像仅dist/whateverpath
在 jpg 和 png 被imagemin-webp-webpack-plugin处理后才存在时,如何在我的文件中引用 .webp 图像?
这是我的配置文件,以防万一它有用:
webpack.config.js
module.exports = {
entry: {
app: [
'./src/index.js'
]
},
output: {
path: path.resolve(__dirname, 'dist/'),
filename: 'assets/js/[name].bundle.js',
},
devtool: 'source-map',
plugins: [
new CleanWebpackPlugin({
dry: false,
cleanOnceBeforeBuildPatterns: ['!index.html']
}),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: './index.html',
minify: false,
chunks: ['app']
}),
new MiniCssExtractPlugin({
filename: 'css/[name].css',
chunkFilename: '[id].css'
}),
new HtmlCriticalWebpackPlugin({
base: 'dist/',
src: 'index.html',
dest: 'index.html',
inline: true,
minify: true,
extract: false,
width: 1351,
height: 1200,
penthouse: {
blockJSRequests: false,
}
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new ImageminWebpWebpackPlugin({
config: [{
test: /\.(jpe?g|png)/,
options: {
quality: 85
}
}],
overrideExtension: true,
detailedLogs: true,
silent: true,
strict: true
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.html$/,
loader: 'html-loader',
query: {
minimize: false
}
},
{
test: /\.(scss)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
},
{
loader: 'css-loader',
options: {
sourceMap: true,
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
plugins: function () {
return [
require('autoprefixer')
];
}
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(png|svg|jpg|gif|webp)$/,
use: {
loader: 'file-loader',
options: {
name: 'assets/images/[name].[ext]',
}
}
},
]
},
};