【发布时间】:2020-04-27 23:18:00
【问题描述】:
尝试加载在 SCSS 中定义并通过 WebPack devServer 提供的 CSS 背景图像。
SCSS 中定义的背景图片被 WebPack 拾取,但不显示在页面上。
我已尝试在 MiniCssExtractPlugin.loader 中设置 publicPath 选项,并查看了我能找到的与此问题相关的所有答案,但无法使其正常工作。
更新:还尝试在file-loader 中设置publicPath 选项。根据文档,这默认为输出 publicPath,这在我的情况下是相同的。
更新:当在 SCSS 中使用绝对路径时,它会作为确切路径编译为 CSS,但由于本地 dev 和 staging 和 prod 都有不同的路径,所以这不起作用。 p>
运行webpack-dev-server时输出的相关部分:
Child mini-css-extract-plugin node_modules/css-loader/index.js??ref--5-1!node_modules/sass-loader/dist/cjs.js??ref--5-2!index.scss:
Asset Size Chunks Chunk Names
pages/index/404@2x.png 29.2 KiB [emitted]
index.scss:
body {
background: url("./pages/index/404@2x.png");
}
CSS 输出:
body {
background: url([object Module]);
}
我的 WebPack 配置:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const outputDir = 'dist/website';
const publicPath = '/web/website/';
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: './index.ts',
output: {
path: path.resolve(__dirname, outputDir),
publicPath: publicPath,
filename: 'bundle.js',
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
use: ['ts-loader'],
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
sourcemap: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.(png|jpe?g|gif|svg|webp)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
path: path.resolve(__dirname, outputDir),
filename: '[name].css',
chunkFilename: '[id].css',
}),
new CleanWebpackPlugin([outputDir]),
],
devServer: {
contentBase: path.join(__dirname, outputDir),
publicPath: publicPath,
port: 9009,
proxy: {
'/': 'http://127.0.0.1:5000/',
},
},
};
index.ts:
import './index.scss';
console.log('WebPack is working!');
【问题讨论】:
-
file-loader 也有额外的选项,outputPath 和 publicPath。你应该对它们感兴趣。当然,开发版本的路径不同,产品的路径也不同;)
-
谢谢!我有这些设置,但删除了它们,因为它们没有任何效果,我相信我的设置与默认设置相同,因为我的
publicPath与output.publicPath相同并且具有outputPath: 'image'但已删除为简单起见。 -
我准备了一个例子,背景是一张照片background-image
-
谢谢!现在看看它。看看我是否可以从这个工作示例中找到解决我的问题的方法。
标签: webpack webpack-dev-server mini-css-extract-plugin