Extract processed CSS as property on VueJS component for run time

Viewed 664

Is it possible to get the CSS for a Vue component, and attach it as a string to a component when building a library for use at runtime?

vue-cli-service build --mode production --target lib --name components src/index.ts

I currently achieve this for some custom js using a custom block:

vue.config.js:

...
 rules: [
      {
        resourceQuery: /blockType=client-script/,
        use: './client-script-block',
      },
   ],
},
...

client-script-block.js:

module.exports = async function () {

  return `export default function (Component) {
      Component.options.__client_script = ${JSON.stringify(this.resourcePath)};
    }`;
};

which then exposed the string in the Vue app that uses the library. But achieving the same thing with CSS doesn't seem to play ball.

1 Answers

You could take a look at this CSS Extraction modules from VueLoader, that extracts the CSS from specific file or files, and stores it in a custom file, that you could then load dynamically in runtime, like:

Install:

npm install -D mini-css-extract-plugin

    

// webpack.config.js
    var MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  // other options...
  module: {
    rules: [
      // ... other rules omitted
      {
        test: /\.css$/,
        use: [
          process.env.NODE_ENV !== 'production'
            ? 'vue-style-loader'
            : MiniCssExtractPlugin.loader,
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    // ... Vue Loader plugin omitted
    new MiniCssExtractPlugin({
      filename: 'style.css'
    })
  ]
}

Reference: https://vue-loader.vuejs.org/guide/extract-css.html#webpack-4:

Another approach:

// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin")

module.exports = {
  // other options...
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          extractCSS: true
        }
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("style.css")
  ]
}

Reference: https://vue-loader-v14.vuejs.org/en/configurations/extract-css.html

Also here you have a complete guide for extracting the CSS from a SSR (Server Side Rendered) apps: https://ssr.vuejs.org/guide/css.html#enabling-css-extraction

Related