我第一次使用Webpack,并且已经能够根据需要处理我的外部CSS和JS文件。我还可以使用 img 标签从HTML文件加载图像。现在,我想像这样加载背景图片:
src / index.html
<div style="background-image: url('img/item.png');" ></div>
上面的代码不起作用,图像甚至没有添加到我的 dist / images 文件夹中。这是我的切入点。
src / index.js
import './js/home.js';
import './css/home.css';
require('./index.html')
这是我的Webpack配置文件:
webpack.conf.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: {
home: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js'
},
plugins: [
new MiniCssExtractPlugin({
publicPath: path.resolve(__dirname, 'dist'),
filename: 'css/[name].css',
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.css$/,
use: [
'css-hot-loader',
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: path.resolve(__dirname, 'dist/css')
}
},
'css-loader'
]
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name:'img/[name].[ext]',
publicPath: '/'
}
}
]
},
{
test: /\.(ttf|eot|svg|woff|woff2|otf)$/,
use:[
{
loader: 'file-loader',
options: {
name:'fonts/[name].otf',
publicPath: '/'
}
}
]
}
]
},
devServer: {
contentBase: './dist',
hot: true,
watchContentBase: true
}
};
什么是正确的方法?