Extract one css file per piece of web package (require.ensure)

When trying to implement page optimization in our application, we want to be able to generate separate CSS files for each piece of the web package in order to improve page rendering performance for the first page of our application. To do this, we tried to use extract-text-plugin in combination with require.ensure as follows:

const $ = require('load-webpack-plugins')(); module.exports = { entry: { 'app': './src/app.js' }, output: { path: 'dist', filename: '[name].js' }, devtool: 'source-map', module: { loaders: [ { test: /\.js$/, use: [{ loader: 'babel-loader' }] }, { test: /\.css$/, use: $.ExtractTextPlugin.extract({ fallback: 'style-loader', use: [{ loader: 'css-loader' }] }) } ] }, plugins: [ new $.ExtractTextPlugin({ filename: '[name].[contenthash].css', allChunks: true }), new $.NamedModulesPlugin(), ] } 

with app.js:

 console.log('this is app.js'); require.ensure([], require => { require('./a.css'); }, 'base'); require.ensure([], require => { require('./b.css'); }, 'first'); require.ensure([], require => { require('./c.css'); }, 'second'); 

and a.css:

 .a { color: red; } 

and b.css:

 .b { color: red; } 

and c.ss:

 .c { color: red } 

The problem is that we get only one dist/app.e2e9da337e9ab8b0ca431717de3bea22.css CSS file with the contents of all 3 pieces:

 .a { color: red; } .b { color: red; } .c { color: red } /*# sourceMappingURL=app.e2e9da337e9ab8b0ca431717de3bea22.css.map*/ 

how are we going to extract one css file per webpack piece (require.ensure) in this case? even if it is supported by extract-text-plugin.

PS: Here is an example repository demonstrating this problem - https://github.com/osdevisnot/extract-text-demo

+5
source share
1 answer

extract-text-plugin is not extracted at split points. {allChunks: true} it extracts all css in all chunks and puts it in a single css file.
But this does not solve your problem.

To do this, you can try extract-css-chunks-webpack-plugin , specially created for this use case, using extract-text-plugin.

+5
source

Source: https://habr.com/ru/post/1265160/


All Articles