提取处理过的 CSS 作为 VueJS 组件上的属性以供运行时使用

Joh*_*hnC 6 javascript webpack vue.js vue-cli

是否可以获取 Vue 组件的 CSS,并在构建供运行时使用的库时将其作为字符串附加到组件?

vue-cli-service build --mode production --target lib --name components src/index.ts
Run Code Online (Sandbox Code Playgroud)

我目前使用自定义块为一些自定义 js 实现了这一点:

vue.config.js:

...
 rules: [
      {
        resourceQuery: /blockType=client-script/,
        use: './client-script-block',
      },
   ],
},
...
Run Code Online (Sandbox Code Playgroud)

客户端脚本块.js:

module.exports = async function () {

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

然后在使用该库的 Vue 应用程序中公开字符串。但是用 CSS 实现同样的事情似乎并不奏效。

JP.*_*let 0

您可以查看VueLoader中的 CSS Extraction 模块,它从特定文件中提取 CSS,并将其存储在自定义文件中,然后您可以在运行时动态加载该文件,例如:

安装:

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'
    })
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

另一种方法:

// 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")
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

另外,这里还有从 SSR(服务器端渲染)应用程序中提取 CSS 的完整指南: https: //ssr.vuejs.org/guide/css.html#enabling-css-extraction