Using ExtractTextPlugin for Webpack, how do you not extract css and create an empty file with a flag?

141 views Asked by At

Basically I want to extract css in production, but I want to leave it in the JavaScript file in development mode.

This is so I can have the sourcemap working which shows the sass files used.

I want to be able to have:

<link href="~/dist/css/site.css" rel="stylesheet" />
<script type="text/javascript" src="~/dist/js/manifest.js"></script>
<script type="text/javascript" src="~/dist/js/css.js"></script>

Documentation is a bit thin on the ground.

So in dev mode site.css will be empty and won't cause an error like it would if it didn't exist. css.js will be used for style and source mapping.

In production mode css.js will exist but just not do anything because the css is extracted. This means the css will load nice and quickly and minified in site.css but have no mapping.

1

There are 1 answers

0
anonfg4rtz4aetae4tata4t On

What I did was this: Installed and required webpack-create-file-plugin Created the css directory with a .empty file in it because the directory must exist.

This is generally how I have done it:

const extractSass = new ExtractTextPlugin("css/site.css");
const sassOptions = removeEmpty([
    ifNotProd({
        loader: "style-loader"
    }),
    {
        loader: "css-loader",
        options: {
            sourceMap: ifNotProd()
        }
    }, {
        loader: "sass-loader",
        options: {
            outputStyle: ifProd("compressed", "expanded"),
            sourceMap: ifNotProd()
        }
    }
]);

The sass rule looks like this:

{
    test: /\.scss$/,
    use: ifProd(extractSass.extract({
        use: sassOptions,
        fallback: "style-loader"
    }), sassOptions)
}

Added to plugins ifNotProd(new CreateFilePlugin({files: ["css/site.css"]})) and ifProd(extractSass)