- webpack 4 关于图片需要使用 file-loader 和 url-loader。
- webpack 5 不需要
- file-loader => asset/resource 把图片拷贝到输出目录里去,返回一个输出路径,包括文件
- url-loader => asset/inline 不拷贝文件,直接把源文件变成 base 64 字符串内嵌到输出结果
使用如下:
/** ./src/index.js **/
import url from './test.jpeg';
let image = new Image();
image.src = url;
document.body.append(image);
/** ./webpack.config.js **/
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devServer: {
port: 8080,
open: true,
compress: true,
static: './dist',
},
entry: {
index: './src/index.js'
},
output:{
path: path.resolve(__dirname, './dist'),
filename: '[name].[hash:8].js'
},
resolve:{
alias: {
'@':path.resolve('src')
}
},
module:{
rules: [
{
test: /\.css$/,
use:[
'style-loader',
{
loader:'css-loader',
},
'postcss-loader'
]
},
{
test:/\.(jpeg|jpg|png|gif)$/,
type:'asset/resource',
generator:{
filename:'[hash][ext]'
}
}
]
},
plugins: [
new webpack.CleanPlugin(),
new HtmlWebpackPlugin({
filename:'index.html',
inject: 'body',
template:'./public/index.html'
})
]
}
如果想要转换成base64, 将 resource 改成 inline 就可以了。