There's more...

Let's implement CSS preprocessors such as Sass, Stylus, and LessCSS:

  1. If you want to extract your CSS code to a style.css file and compress the code for production mode, you can use the extract-text-webpack-plugin package:
   npm install [email protected]
  1. We need to add this to our Webpack plugins:
  import HtmlWebPackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

const isProduction = process.env.NODE_ENV === 'production';

const plugins = [
new HtmlWebPackPlugin({
title: 'Codejobs',
template: './src/index.html',
filename: './index.html'
})
];

if (isProduction) {
plugins.push(
new ExtractTextPlugin({
allChunks: true,
filename: './css/[name].css'
})
);
}

export default plugins;
File: webpack/configuration/plugins.js
  1. As you can see, I'm pushing to the plugins array only if is production. This means we need to create a new script into our package.json to specify when we are going to use production:
    "scripts": {
"start": "webpack-dev-server --mode development --open",
"start-production": "NODE_ENV=production webpack-dev-server --
mode
production",
"build-development": "webpack --mode development",
"build": "webpack --mode production"
}
  1. Run npm run start-production in your terminal, and you will be able to start in production mode.
  2. You will probably get some errors because we also need to add a rule for the Extract Text Plugin to our module node:
  import ExtractTextPlugin from 'extract-text-webpack-plugin';

const isProduction = process.env.NODE_ENV === 'production';

const rules = [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader'
}
];

if (isProduction) {
rules.push({
test: /.scss/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader?minimize=true&modules=true&localIdentName=
[name]_[local]_[hash:base64]',
'sass-loader'
]
})
});
} else {
rules.push({
test: /.scss$/, // .scss - .styl - .less
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
localIdentName: '[name]_[local]_[hash:base64]',
sourceMap: true,
minimize: true
}
},
{
loader: 'sass-loader' // sass-loader, stylus-loader or
//less-loader

}
]
});
}

export default {
rules
};
  1. We are using Extract Text Plugin just for production. For any other environment, we use style-loader, css-loader, and sass-loader directly as before. That's why I love splitting the Webpack configuration into smaller files, as you can see, some of the files can be huge, so this helps us to be more organized. If you start the production mode with npm run start-production, you will see this CSS:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset