迁移到 webpack5 并更新所有库后,我遇到了这个问题。
这是我的 webpack 配置:
const path = require('path');
const glob = require('glob');
const {ProvidePlugin} = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const WebpackNotifierPlugin = require('webpack-notifier');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const {watch, assetsRoot, assetsPublicPath, assetsSubDirectory} = require('./config');
const getAssetsPath = (_path, dir) => {
return path.posix.join(dir ? dir : assetsSubDirectory, _path);
};
const getPlugins = () => {
if (watch) {
return [
new BrowserSyncPlugin({
proxy: 'https://mysite/',
host: 'mysite.com',
port: '3000',
open: 'external',
}),
];
}
return [
// Extract CSS into its own file
new MiniCssExtractPlugin({
filename: getAssetsPath('[name].[hash].css', 'css'),
}),
];
};
module.exports = {
mode: watch ? 'development' : 'production',
devtool: watch ? 'inline-source-map' : 'source-map',
watch,
entry: {
app: [
...glob.sync('./assets/js/**/*.js'),
'./assets/sass/app.scss',
...glob.sync('./assets/css/**/*.css'),
],
react: './react/index.js',
},
output: {
path: assetsRoot,
filename: getAssetsPath(`[name]${watch ? '' : '.[hash]'}.js`, 'js'),
publicPath: assetsPublicPath,
clean: true,
assetModuleFilename: '[name][ext]'
},
resolve: {
extensions: ['.js', '.jsx', 'css', 'scss'],
modules: [path.join(__dirname, '..', 'node_modules'), 'node_modules'],
},
optimization: {
minimizer: [new CssMinimizerPlugin()],
},
plugins: [
...getPlugins(),
new ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
}),
new WebpackNotifierPlugin(),
new WebpackManifestPlugin(),
new CssMinimizerPlugin(),
new Dotenv(),
],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.s?css$/,
use: [
{
loader: watch ? 'style-loader' : MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
},
},
'scoped-css-loader',
'sass-loader',
]
},
{
test: /\.svg?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/',
}
}
],
},
{
test: /\.(png|jpe?g|gif)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/',
}
}
],
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/',
}
}
],
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/',
},
},
],
},
],
}
};
当我运行本地环境时,我注意到 fa-icons 库中的图像和图标不存在。所以我找出了问题的原因,我在浏览器的控制台中看到我的图像路径已从 mysite.com/build/static/image.jpg 更改为 mysite.com/build/image.jpg。当我尝试手动更改路径时 - 我看到图像。那么为什么它跳过了 /static/ 部分?
assetModuleFilename: 'folder/[name][ext]
并添加所需类型。