Webpack 4. Compile scss to separate css file

白昼怎懂夜的黑 提交于 2019-12-05 03:55:16

You need to use the MiniCssExtractPlugin. This will extract your css into a separate file.

There are a few parts of your webpack.config.js file you'll need to add to, or change.

You'll need to require the plugin at the top of the file:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

A plugins property is also required in the modules object:

plugins: [
  new MiniCssExtractPlugin({
    filename: "[name].css",
    chunkFilename: "[id].css"
  })
]

And you'll need to change your scss rule. Note the test is slightly different to include .scss files (probably best to name you scss files .scss) and the addition of the sass-loader which you'll need to install with npm. The loaders in the 'use' array operate in reverse order, so sass-loaded goes first, converting scss to css, then the css-loader and then extract plugin extracts the css out again to a separate file:

{
    test: /\.s?css$/,
    use: [
      MiniCssExtractPlugin.loader,
      "css-loader",
      "sass-loader"
    ]
}

So I think your config file will change to this:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var path = require("path");

module.exports = {
    entry: "./js/main.js",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js",
        publicPath: "/dist"
    },
    watch:true,
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: "babel-loader",
                    options: { presets: ["es2015"] }
                }
            },
            {
                test: /\.s?css$/,
                use: [
                  MiniCssExtractPlugin.loader,
                  "css-loader",
                  "sass-loader"
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
          filename: "[name].css",
          chunkFilename: "[id].css"
        })
    ]
}

Hope that helps.

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