search

Home  >  Q&A  >  body text

Tree shake, sideEffects and CSS of Vue and Webpack: Load CSS files of unused components

<p>We are trying to figure out the correct way to handle CSS trees in Vue single file components when using Webpack. </p> <p>In package.json, I have: <code>"sideEffects": ["*.css", "*.less","*.vue" ]</code>, This seems to correctly prevent Vue components from loading when they shouldn't. However, every single <code><style></code> tag will be loaded onto the page. </p> <p>We load our SFC from an NPM package, which lists a series of exports, for example: </p> <pre class="brush:php;toolbar:false;">export blah from 'blah.vue'; export blah2 from 'blah2.vue'; export blah3 from 'blah3.vue';</pre> <p>Even if we just have <code>import { blah3 } from 'a-npm-package';</code> in our JavaScript, it will include the styles for all three components. Since we have a lot of Vue components, this results in a lot of unused CSS being added to the page. </p> <p>How do we prevent this from happening? There are definitely better, more dynamic ways of handling styles rather than just dumping them all into the page, even if only 1/10 of them are used. </p> <p>Thank you</p>
P粉068174996P粉068174996460 days ago586

reply all(1)I'll reply

  • P粉884548619

    P粉8845486192023-08-26 09:13:35

    You can use MiniCssExtractPlugin to perform CSS tree shaking. If you are using scss or sass, you can add these loaders as well.

    // webpack.config.js (production)
    const path = require('path')
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    
    module.exports = {
      mode: 'production',
    
      entry: path.resolve('src/index.js'),
    
      output: {
        filename: '[name].js',
        path: path.resolve('dist'),
      },
    
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
          },
          {
            test: /\.css$/,
            exclude: /node_modules/,
            use: [
              // 将css提取到文件中
              MiniCssExtractPlugin.loader,
              // 处理你的应用程序中的`.css`文件的导入
              'css-loader',
            ],
          },
        ],
      },
      plugins: [
        // 将所有的css提取到一个单独的文件中
        new MiniCssExtractPlugin({
          filename: '[name].css',
        }),
      ],
    }

    reply
    0
  • Cancelreply