【问题标题】:Error while importing font or images file inside scss using Webpack 4 and react js使用 Webpack 4 和 react js 在 scss 中导入字体或图像文件时出错
【发布时间】:2019-12-15 12:05:38
【问题描述】:

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

我尝试了很多解决方案,但都没有解决我的问题,

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

【问题讨论】:

  • 字体文件周围有文件夹吗?
  • 是的,我的字体在一个文件夹中。
  • 我的意思是问它可能在嵌套文件夹中,所以文件夹结构不正确?
  • 我无法在此处添加图像,所以我已在驱动器中添加,因此您可以清楚地看到我的文件夹结构drive.google.com/file/d/1f5n9JSR1a3NNt2v7ng4pAf7XOpO5-VHy/…
  • 你能发张打开字体文件夹的图片吗?

标签: reactjs webpack-4


【解决方案1】:

您需要记住,导入实际上是从根 index.scss 文件(加载所有其他部分文件的文件)“进行”的。因此,您用于获取资产的路径不准确。

您需要使用./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

【讨论】:

  • 谢谢您,我可以按照您的建议解决问题。
猜你喜欢
  • 2021-06-28
  • 2019-01-10
  • 2018-09-13
  • 2019-11-20
  • 1970-01-01
  • 2020-02-16
  • 2019-05-05
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多