Tree shake, sideEffects and CSS of Vue and Webpack: Load CSS files of unused components
P粉068174996
2023-08-25 10:22:08
<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>
You can use MiniCssExtractPlugin to perform CSS tree shaking. If you are using scss or sass, you can add these loaders as well.