带sass-loader的Webpack文件加载器 [英] Webpack file-loader with sass-loader

查看:245
本文介绍了带sass-loader的Webpack文件加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是nodejs的新手,尝试在其上使用sass时遇到问题.

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.


场景:

我具有以下文件夹结构:

I have the following folder structure:

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

目标:

我想使用webpack将style.scss编译为style.css并将其放置在dist/frontend/css/目录中,因此应得到以下路径:dist/frontend/css/style.css并创建以下文件夹结构:

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


代码:

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


结果:

我收到此消息:

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

问题

  1. 为什么会这样?

  1. Why is that happening?

实现目标的正确代码是什么?

What is the correct codes to achieve the Goal?

推荐答案

如消息所述,此路径无效:'./scss/style.scss'.定义路径时有错别字.该文件夹应该是sass而不是scss.

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

它的作用类似于Mini CSS Extract Plugin,但是当用于将多个.scss文件转换为不同的.css文件时,不会为每个.css文件生成其他.js文件.

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.

这篇关于带sass-loader的Webpack文件加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆