首页 > 解决方案 > 尝试添加 .scss 文件时 webpack 无法构建

问题描述

已编辑:我修复了 scss 文件的正则表达式(这实际上是一个错字,因为我将其发布到堆栈溢出,但我一直遇到这个问题,正则表达式输入正确。)但它没有修复问题。我仍然收到一个不完整的构建和错误消息,告诉我我没有为我试图捆绑的 .scss 文件安装加载程序,即使我已经安装了 node-sass sass-loader css-loader 和 style-loader , css 文件导入,配置规则正确写出。

我将包含我的 package.json、webpack.config.js 和 index.js 的副本,但据我对我现在正在处理的课程材料的理解,我正确安装了所有依赖项,添加了正确的配置文件的规则,并正确导入我的 index.js 中的 scss 文件。但是,每次我尝试构建时,它都会失败并告诉我我的 .scss 文件没有正确的加载器。

任何帮助是极大的赞赏。这是我第一次尝试使用 sass 设置 webpack。

包.json:

{
  "name": "example-project",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/server/index.js",
    "build-prod": "webpack --config webpack.prod.js",
    "build-dev": "webpack-dev-server --config webpack.dev.js --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.17.1",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  },
  "devDependencies": {
    "@babel/core": "^7.8.3",
    "@babel/preset-env": "^7.8.3",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.4.2",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.0",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.2",
    "webpack-dev-server": "^3.10.1"
  }
}

webpack 配置文件:

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  mode: "production",
  entry: "./src/client/index.js",
  module: {
    rules: [
      {
        test: '/.js$/',
        exclude: /node_modules/,
        loader: "babel-loader"
      },
      {
        test: '/\.scss$/',
        use: ['style-loader', 'css-loader', 'sass-loader']
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/client/views/index.html",
      filename: "./index.html"
    }),
    new CleanWebpackPlugin({
      // Simulate the removal of files
      dry: true,
      // Write Logs to Console
      verbose: true,
      // Automatically remove all unused webpack assets on rebuild
      cleanStaleWebpackAssets: true,
      protectWebpackAssets: false
    })
  ]
};

index.js

import { handleSubmit } from "./js/formHandler";
import { nameChecker } from "./js/nameChecker";


import "./styles/resets.scss";
import  "./styles/base.scss";
import  "./styles/footer.scss";
import  "./styles/form.scss";
import "./styles/header.scss";

alert("this happened");

标签: webpacksass

解决方案


将这些行复制粘贴到我的规则中解决了我的问题。


      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },

推荐阅读