美文网首页我爱编程
Code Splitting - CSS

Code Splitting - CSS

作者: 卢泉威 | 来源:发表于2017-03-19 10:22 被阅读0次

    To bundle CSS files with webpack, import CSS into your JavaScript code like any other module, and use the css-loader (which outputs the CSS as JS module), and optionally apply the ExtractTextWebpackPlugin
    (which extracts the bundled CSS and outputs CSS files).

    Importing CSS

    Import the CSS file like a JavaScript module, for instance in vendor.js:

    import 'bootstrap/dist/css/bootstrap.css';
    

    Using css-loader

    Configure the css-loader in webpack.config.js as follows:

    module.exports = {
        module: {
            rules: [{
                test: /\.css$/,
                use: 'css-loader'
            }]
        }
    }
    

    As a result, the CSS is bundled along with your JavaScript.

    This has the disadvantage that you will not be able to utilize the browser's ability to load CSS asynchronously and parallel. Instead, your page will have to wait until your whole JavaScript bundle is loaded, to style itself.

    Using ExtractTextWebpackPlugin

    Install the ExtractTextWebpackPlugin plugin as follows

    npm i --save-dev extract-text-webpack-plugin
    

    To use this plugin, it needs to be added to the webpack.config.js file in three steps.

    +var ExtractTextPlugin = require('extract-text-webpack-plugin');
    module.exports = {
        module: {
             rules: [{
                 test: /\.css$/,
    -            use: 'css-loader'
    +            use: ExtractTextPlugin.extract({
    +                use: 'css-loader'
    +            })
             }]
         },
    +    plugins: [
    +        new ExtractTextPlugin('styles.css'),
    +    ]
    }
    

    With above two steps, you can generate a new bundle specifically for all the CSS modules and add them as a separate tag in the index.html.

    相关文章

      网友评论

        本文标题:Code Splitting - CSS

        本文链接:https://www.haomeiwen.com/subject/wxdmnttx.html