這是我的webpack生產(chǎn)環(huán)境的配置文件
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
mode: 'production',
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
return path.relative(path.dirname(resourcePath), context) + "/assets/images/";
},
},
},
{
loader: 'css-loader',
}
],
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: '[name].[contenthash].[ext]',
outputPath: 'assets/images',
publicPath: '/assets/images',
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'url-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'assets/fonts',
publicPath: '/assets/fonts',
},
},
],
},
]
},
entry: {
index: './src/pages/index/index.js'
},
output: {
path: path.resolve(__dirname, '../public/'),
filename: '[name].[contenthash:8].js',
publicPath: './',
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/pages/index/index.html',
chunks: ['index']
}),
new MiniCssExtractPlugin({
filename: 'assets/css/[name].[contenthash:8].css',
}),
new CleanWebpackPlugin()
],
resolve: {
alias: {
'@': path.resolve(__dirname, '../src/'),
}
},
};
我嘗試使用url-loader來處理圖像和字體文件,我在css中使用url()來引用這些文件,但是在構(gòu)建之后,這些文件沒有像預(yù)期的那樣在assets/image和assets/fonts目錄中生成,而是直接在構(gòu)建目錄的根目錄中生成,文件的內(nèi)容是JavaScript代碼,文件擴(kuò)展名看起來像普通文件,但是文件內(nèi)容和文件擴(kuò)展名完全不同
例如,svg文件的內(nèi)容是 導(dǎo)出默認(rèn)值& quot/assets/images/filname . hash . SVG & quot;;
假設(shè)它的文件名是a.svg,路徑是build/a.svg,在頁(yè)面中,也是直接通過。/a.svg,但文件內(nèi)容為/assets/images/b.svg,瀏覽器無法正常顯示。正常情況下瀏覽器應(yīng)該是直接引用/assets/images/b.svg,而不是這個(gè)偶然的產(chǎn)物,這是為什么呢?
我的webpack版本是webpack 5,但是我在看webpack 4的文檔,這是錯(cuò)誤的。在webpack 5中,不再需要使用url加載器或文件加載器,在webpack 5中,文件應(yīng)該以這種方式處理
module.exports = {
...
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
generator: {
filename: 'assets/images/[hash][ext][query]'
}
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: 'assets/fonts/[hash][ext][query]'
}
},
}