将 css-loader 更新到 v4 后无法解析“/images/bg.jpg”

问题描述 投票:0回答:2

css-loader 的版本为 3.5.3,我的应用程序运行良好。将其更新为 4.3.0,现在我收到以下编译错误。在查看升级到 v4 所固有的“重大更改”时,我无法弄清楚为什么。

可能与我在 .scss 文件中使用 url 有关,其中存在对 /images/bg.jpg 的唯一引用?我有一个 styles.scss 文件,它导入一个“_box-layout.scss”文件,其中:

.box-layout {
  align-items: center;
  background: url('/images/bg.jpg');
  background-size: cover;
  display: flex;
  height: 100vh;
  justify-content: center;
  width: 100vw;
}

编译错误:

ERROR in ./src/styles/styles.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve '/images/bg.jpg' in 'C:\Users\gwich\dev\javascript\react\rental-props\src\styles'
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\Resolver.js:209:21
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\Resolver.js:285:5
    at eval (eval at create (C:\Users\gwich\dev\javascript\react\rental-props\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:13:1)
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\UnsafeCachePlugin.js:44:7
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\Resolver.js:285:5
    at eval (eval at create (C:\Users\gwich\dev\javascript\react\rental-props\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:13:1)
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\Resolver.js:285:5
    at eval (eval at create (C:\Users\gwich\dev\javascript\react\rental-props\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:25:1)
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\DescriptionFilePlugin.js:67:43
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\enhanced-resolve\lib\Resolver.js:285:5
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\webpack\lib\NormalModule.js:316:20
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\loader-runner\lib\LoaderRunner.js:367:11
    at C:\Users\gwich\dev\javascript\react\rental-props\node_modules\loader-runner\lib\LoaderRunner.js:233:18
    at context.callback (C:\Users\gwich\dev\javascript\react\rental-props\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at Object.loader (C:\Users\gwich\dev\javascript\react\rental-props\node_modules\css-loader\dist\index.js:154:5)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
 @ ./src/app.js 13:0-30
 @ multi babel-polyfill ./src/app.js

我的 webpack 配置(如果感兴趣的话):

const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

process.env.NODE_ENV = process.env.NODE_ENV || "development";

if (process.env.NODE_ENV === "test") {
  require("dotenv").config({ path: ".env.test" });
} else if (process.env.NODE_ENV === "development") {
  require("dotenv").config({ path: ".env.development" });
}

module.exports = (env) => {
  const isProduction = env === "production";

  return {
    entry: ["babel-polyfill", "./src/app.js"],
    output: {
      path: path.join(__dirname, "public", "dist"),
      filename: "[name].js",
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'initial',
          },
        },
      },
    },
    mode: isProduction ? 'production' : 'development',
    module: {
      rules: [
        {
          loader: "babel-loader",
          test: /\.js$/,
          exclude: /node_modules/,
        },
        {
          test: /\.less$/,
            use: [
              {
                loader: MiniCssExtractPlugin.loader,
                options: {
                  sourceMap: !isProduction,
                },
              },
              {
                loader: "css-loader",
                options: {
                  sourceMap: !isProduction,
                },
              },
              {
                loader: "less-loader",
                options: {
                  sourceMap: !isProduction,
                  modifyVars: {
                    "primary-color": "#1c88bf",
                    "link-color": "#1c88bf",
                    "border-radius-base": "2px",
                  },
                  javascriptEnabled: true,
                },
              }
            ],
        },
        {
          test: /\.s?css$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                sourceMap: !isProduction,
              },
            },
            {
              loader: "css-loader",
              options: {
                sourceMap: !isProduction,
              },
            },
            {
              loader: "sass-loader",
              options: {
                sourceMap: !isProduction,
              },
            },
          ],
        },
        {
          test: /\.(svg|eot|ttf|woff|woff2)$/,
          use: {
            loader: "file-loader",
            options: {
              name: "[name].[ext]",
              outputPath: "fonts/",
            },
          },
        },
      ],
    },
    plugins: [
      // new BundleAnalyzerPlugin(),
      new MiniCssExtractPlugin({ filename: '[name].css'}),
      new webpack.DefinePlugin({
        "process.env.FIREBASE_API_KEY": JSON.stringify(process.env.FIREBASE_API_KEY),
        "process.env.FIREBASE_AUTH_DOMAIN": JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
        "process.env.FIREBASE_DATABASE_URL": JSON.stringify(process.env.FIREBASE_DATABASE_URL),
        "process.env.FIREBASE_PROJECT_ID": JSON.stringify(process.env.FIREBASE_PROJECT_ID),
        "process.env.FIREBASE_STORAGE_BUCKET": JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
        "process.env.FIREBASE_MESSAGING_SENDER_ID": JSON.stringify(process.env.FIREBASE_MESSAGING_SENDER_ID),
      }),
    ],
    devtool: isProduction ? "source-map" : "inline-source-map",
    devServer: {
      contentBase: path.join(__dirname, "public"),
      historyApiFallback: true,
      publicPath: "/dist/",
    },
  };
};
css webpack css-loader
2个回答
1
投票

感谢这篇文章,我成功解决了这个问题。

首先,我安装了

url-loader

npm install url-loader --save-dev

接下来,我在规则部分的

webpack.config.js
文件中更新了后台 url 中的路径(图像位于
/public/images/bg.jpg
,而我的
_box-layout.scss
文件位于
/src/styles/components/ imported by /src/styles/styles.scss
):

  rules: [
    {
      test: /\.(png|jpg)$/,
      loader: 'url-loader'
    },

最后,我更新了我的

_box-layout.scss
文件:

.box-layout {
  align-items: center;
  background: url('../../public/images/bg.jpg');
  background-size: cover;
  display: flex;
  height: 100vh;
  justify-content: center;
  width: 100vw;
}

0
投票

从 css-loader 3.6.0 更新到 5.2.7 后遇到同样的问题。通过更改 webpack 配置从

 禁用 
css-loader
 解析 
url

路径解决了这个问题
{
    loader: "css-loader",
},

{
    loader: "css-loader",
    options: {
        url: false
    }
},

https://github.com/webpack-contrib/css-loader#url 中所述,默认为

true

允许启用/禁用处理 CSS 函数 url 和图像集。如果设置为 false,css-loader 将不会解析 url 或 image-set 中指定的任何路径。还可以传递一个函数来根据资产的路径动态控制此行为。从4.0.0版本开始,根据服务器根解析绝对路径。

© www.soinside.com 2019 - 2024. All rights reserved.