Skip to content

Instantly share code, notes, and snippets.

@kalpeshsingh
Created October 14, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalpeshsingh/d7d305b620c1a671d3f9f037c7656284 to your computer and use it in GitHub Desktop.
Save kalpeshsingh/d7d305b620c1a671d3f9f037c7656284 to your computer and use it in GitHub Desktop.
webpack-extract-css-demo
/** native nodejs packages **/
const path = require("path");
const fs = require("fs");
/** post css import css **/
const postCssImport = require("postcss-import");
/** extract css plugin **/
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
/** webpack optimization plugin **/
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserJSPlugin = require("terser-webpack-plugin");
// get entries for multiple files
const getEntries = () => {
const componentsPath = path.resolve(__dirname, "src/components");
const components = fs.readdirSync(componentsPath);
const entries = {};
components.map(component => {
entries[component] = `./src/components/${component}/index.js`;
});
return entries;
};
module.exports = {
entry: getEntries(),
output: {
path: path.resolve(__dirname, "./out"),
filename: "[name].js",
libraryTarget: "commonjs2"
},
externals: ["react", "react-dom"],
resolve: {
modules: [path.resolve(__dirname, "src"), "node_modules"]
},
optimization: {
splitChunks: {
cacheGroups: {
styles: {
name: "styles",
test: /\.css$/,
chunks: "all",
enforce: true
}
}
},
minimizer: [
new TerserJSPlugin({}),
new OptimizeCSSAssetsPlugin({
cssProcessorPluginOptions: {
preset: ["default"]
}
})
]
},
mode: "production",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: "css-loader",
options: {
camelCase: true,
importLoaders: 1,
import: true,
modules: true
}
},
{
loader: "postcss-loader",
options: {
ident: "postcss",
plugins: () => [
postCssImport({
path: ["src"]
})
]
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "sample.[name].[contentHash].css"
})
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment