使用 Webpack 4 和 React js 在 scss 中导入字体或图像文件时出错

Error while importing font or images file inside scss using Webpack 4 and react js

我正在使用 webpack 和 React js。 当我尝试在我的 scss 文件中导入图像或字体文件时出现此错误。

我尝试了很多解决方案,但 none 解决了我的问题,

webpack.common.js enter image description here

const path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: {
    main: "./src/index.js",
    vendor: "./src/vendor.js"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.html$/,
        use: ["html-loader"]
      },
      {
        test: /\.(ttf|svg|png|jpg|gif)$/,
        use: {
          loader: "file-loader",
          options: {
            name: "[name].[hash].[ext]",
            outputPath: "imgs"
          }
        }
      }
    ]
  }
};

这是另一个webpack.dev.js

module.exports = merge(common, {
  mode: "development",
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist")
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/template.html"
    })
  ],
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          "style-loader", //3. Inject styles into DOM
          "css-loader", //2. Turns css into commonjs
          "sass-loader" //1. Turns sass into css
        ]
      }
    ]
  }
});

错误./src/assets/index.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./src/assets/index.scss) 找不到模块:错误:无法解析 'C:\Users\jamal\Documents\webpack-demo-app\src\assets' 中的“../../../src/assets/fonts/icomoon.ttf” @./src/index.js @multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

您需要记住,导入实际上是从根 index.scss 文件(加载所有其他部分的文件)中获取 "place"。所以你用来获取资产的路径不准确。

您需要使用 ./fonts/icomoon.ttf 而不是 ../fonts/icomoon.ttf

你的文件结构:

assets/
------/fonts
------/images
------/sass
------/---/partial1.scss // while the reference to the image is here
------/index.scss        // the actual root of the reference call is here