1. 程式人生 > >webpack學習(九):配置sass

webpack學習(九):配置sass

demo地址: https://github.com/Lkkkkkkg/webpack-demo
繼上一次配置完react: https://blog.csdn.net/qq593249106/article/details/84928595

安裝

sass 是預編譯語言, 瀏覽器無法直接識別, 需要進行編譯成 css 檔案, 所以編譯 sass 需要安裝 sass-loader , sass-loader 又依賴於 node-sass, 編譯成 css 之後, 還需要用到 style-loader css-loader 來打包, 所以都需要安裝

npm install node-sass sass-
loader style-loader css-loader --save-dev

在 src 目錄下新建一個 sass.scss 用來測試, 這裡用的是 scss 的語法:

|- /node_modules
|- /src //用於放原始檔的資料夾
  |- /components
    |- /index //模板檔案
      |- index.html //模板檔案
      |- index.js //入口檔案
      |- App.js //入口檔案
      |- index.scss//入口檔案
|- package.json
|- webpack.config.js //webpack配置檔案

index.scss

$color: green;

body {
  background-color: $color;
}

在 index.js 中引入 sass 檔案:
index.js

import React from 'react'
import { render } from 'react-dom'
import App from './App'
import './index.scss'

render(<App />, document.getElementById("root"))

配置 webpack.config.js

安裝了 loader 後, 在 webpack 配置檔案中配置一下讓它生效:
webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');


module.exports = {
    mode: 'development',
    entry: './src/components/index/index.js', //入口檔案
    devtool: 'inline-source-map', // 不同選項適用於不同環境
    devServer: {
        contentBase: './dist', //將dist目錄下的檔案(index.html)作為可訪問檔案, 如果不寫這個引數則預設與webpack.cofig.js的同級目錄
        port: 8080 //埠號設為8080, 預設也是8080
    },
    module: {
        rules: [ //配置載入器, 用來處理原始檔, 可以把es6, jsx等轉換成js, sass, less等轉換成css
            {
                exclude: /node_modules|packages/, //路徑
                test: /\.js$/, //配置要處理的檔案格式,一般使用正則表示式匹配
                use: 'babel-loader', //使用的載入器名稱
            },
            {
                test: /\.scss/, //配置sass轉css
                use: [
                    {loader: 'style-loader'}, {loader: 'css-loader'}, {loader: 'sass-loader'}
                ]
            }
        ]
    },
    plugins: [ //webpack 通過 plugins 實現各種功能, 比如 html-webpack-plugin 使用模版生成 html 檔案
        new CleanWebpackPlugin(['dist']), //設定清除的目錄
        new HtmlWebpackPlugin({
            filename: 'index.html', //設定生成的HTML檔案的名稱, 支援指定子目錄,如:assets/admin.html
            template: "./src/components/index/index.html" //指定模板檔案的位置
        })
    ],
    output: {
        filename: 'bundle.js', //根據入口檔案輸出不同出口檔案
        path: path.resolve(__dirname, 'dist')
    }
};

執行伺服器

終端輸入 npm run dev, 彈出網頁, 背景為綠色, sass 檔案生效, 配置成功
在這裡插入圖片描述