问题
Im trying to compile scss into a separate css file with no luck. As it is now the css gets into the bundle.js together with all js code. How can i separate my css into its own file?
This is how my config looks.
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: /\.scss$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader"
},
{
loader: "sass-loader"
}
]
}
]
}
};
回答1:
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.
来源:https://stackoverflow.com/questions/50394789/webpack-4-compile-scss-to-separate-css-file