Jamal Abbasi
Jamal Abbasi

Reputation: 13

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

I am using webpack and react js. I am getting this error when i try to import image or font file inside my scss file.

I have tried many solutions but none of them solved my problem,

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"
          }
        }
      }
    ]
  }
};

Here is another 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
        ]
      }
    ]
  }
});

ERROR in ./src/assets/index.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./src/assets/index.scss) Module not found: Error: Can't resolve '../../../src/assets/fonts/icomoon.ttf' in 'C:\Users\jamal\Documents\webpack-demo-app\src\assets' @ ./src/index.js @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

Upvotes: 1

Views: 1210

Answers (1)

aviya.developer
aviya.developer

Reputation: 3613

You need to remember that the import actually takes "place" from the root index.scss file (the one that loads all the other partials). So the path you are using to fetch the asset is not accurate.

You need to use ./fonts/icomoon.ttf instead of ../fonts/icomoon.ttf

your file structure:

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

Upvotes: 1

Related Questions