7

I have a Vue.js project using Vue UI with Webpack project using router for multiple "pages". I am using SASS (SCSS) partials and importing them in the individual components.

<style lang="sass">
@import "@/css/modules/_style-guide.scss";
</style>

On each "page" the SASS (actually the rendered CSS) is being loaded into the DOM in the head for all components even if they are not being imported into the "page".

Adding the "scoped" option still loads all SASS files, just adds the unique guid.

I would rather import the SASS only if a component is present on a "page".

Is there a way to do this?

Cienwen
  • 107
  • 3
  • 10
  • It's part of the build process so it will be auto injected. You can always create a system which fetches some style and add it dynamically to the page. Handle creating & destroying the styles in [`beforeCreate`](https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram) & `beforeDestroy` hooks. – A1rPun Mar 19 '19 at 23:08
  • It should import only when you navigate to certain routes containing the SASS imports. – Yom T. Mar 20 '19 at 01:51
  • @jom That is the behavior I was expecting but it is importing the styles for ALL routes before you navigate to them. – Cienwen Mar 20 '19 at 13:16

1 Answers1

0

Not only do you need to include scoped, you also need to implement lazy loading for all of your components.

If you import like this:

import vue from 'vue'
import MyComponent from '/where/it/is'
vue.component('my-component', MyComponent)

then you would change it to

import vue from 'vue'
const MyComponent = () => import(/* webpackChunkName: "unique-chunk-name" */ '/where/it/is')
vue.component('my-component', MyComponent)

Now MyComponent is lazy loaded - it will only fully load its .js and .css portion of the bundle when it is loaded onto a page

whendon
  • 169
  • 1
  • 12