Webpack file-loader with sass-loader

倾然丶 夕夏残阳落幕 提交于 2019-12-23 20:09:12

问题


I am new to nodejs and get a problem when trying to use sass with it.

The following information is just fictional, but it represents the actual condition.


THE SCENARIO:

I have the following folder structure:

frontend/
 - scss/
  - style.scss
 - main.js
webpack.config.js

Goal:

I want to compile the style.scss to style.css using webpack and put it inside dist/frontend/css/ directory, so it should be resulting this path: dist/frontend/css/style.css and create the following folder structure:

dist/
 - frontend/
   - scss/
     - style.scs
   - main.js
frontend/
     - scss/
      - style.scss
     - main.js
webpack.config.js

THE CODES:

main.js

import `style from "./scss/style.scss";`

webpack.config.js

 module.exports = {
     mode: "development",
     entry: {
       main: "./frontend/main.js"
     },
     output: {
      path: path.join(__dirname, "/dist/frontend"),
      publicPath: "/",
      filename: "[name].js"
     },
     module: {
       rules: [ 
        {
           test: /\.(s*)css$/,
           use: [
             {
               loader: "file-loader",
               options: {
                 name: "css/[name].[ext]"
               }
             },
             "style-loader/url",
             "css-loader?-url",
             "sass-loader"
           ] 
         }
       ]
   }

THE RESULT:

I get this message:

Module not found: Error: Can't resolve './scss/style.scss' in 'E:\project_name\frontend'


THE QUESTIONS

  1. Why is that happening?

  2. What is the correct codes to achieve the Goal?


回答1:


As the message said, this path is not valid: './scss/style.scss'. There are typo when defining the path. The folder is supposed to be sass instead of scss.

The following configuration will work to achieve the Goal mentioned in the question:

 module: {
   rules: [
      {
    test: /\.(s*)css$/,        
    use: [
      "style-loader/url",
      {
        loader: "file-loader",
        options: {
          name: "css/[name].css"
        }
      },
      "sass-loader"
    ]
  }
 ]
}

It works like Mini CSS Extract Plugin, but does not generating additional .js files for each .css file when used to convert multiple .scss files into different .css files.



来源:https://stackoverflow.com/questions/55035376/webpack-file-loader-with-sass-loader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!