I have read tons of tutorials and looked at more Github repos than I care to remember but I'm really struggling to setup Webpack 3 to do the following:
- Compile SASS into CSS
- Create a CSS file within a dist directory
- Run Autoprefixer on CSS
Below is my webpack.config.js:
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
context: path.resolve(__dirname, 'src'),
entry: {
app: './js/index.js',
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist', // New
},
devServer: {
contentBase: path.resolve(__dirname, 'src'), // New
},
module: {
rules: [
{
test: /\.js$/i,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: { presets: ['env'] },
}],
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(sass|scss)$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
]
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'css/styles.css',
allChunks: true,
}),
]
};
At the moment:
- the webpack dev server is running.
- Styles are copied from src/scss/styles.scss to an inline style block within the HTML file served from src/index.html.
I would like a dist directory to be created with a styles.css file within it which I could then link to from within my HTML.
Thanks
You are currently correctly compiling SASS into CSS with
The CSS is not being extracted into an external file because of
style-loader
in the previously described loader chain.style-loader
internalizes all CSS passed to it within a<style>
.To create an external file you can use, which you are,
extract-text-webpack-plugin
. The only problem is that it is not attached to the/\.(sass|scss)$/
test.You only need to create rules for your source files. Since you are writing SASS/SCSS, you do not need a
/\.css$/
test. Your CSS should be extracted if you change your loader chain toNow, to autoprefix your CSS, you'll need to add another loader into the chain,
postcss-loader
. Install it along withautoprefixer
.Add the require for
autoprefixer
at the top of yourwebpack.config.js
.Finally, add
postcss-loader
to the loader chain, in betweencss-loader
andsass-loader
.