css - 从 SCSS 中提取 CSS 并在 React 应用程序中延迟延迟加载

标签 css reactjs webpack lazy-loading

我有几个 SCSS 主题文件,我想将它们提取到 CSS 文件中,然后将它们加载到页面中。我希望能够使用 contenthash 进行长期缓存。

因为我使用的是 Webpack 4,所以我也在使用 mini-css-extract-plugin .我开始在我的 webpack 配置中创建一个 splitChunks。

// webpack.config.js
module.exports = {
  plugins: [
      new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].[contenthash].css",
      chunkFilename: "[id].[contenthash].css"
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        'vendor': {
            // custom commons chunk for js
        },
        'theme-a': {
            test: /theme-a.\scss/,
        },
        'theme-b': {
            test: /theme-b.\scss/,
        },
        // more themes
      }
    }
  }
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader"
        ]
      }
    ]
  }
}

然后我尝试了 dynamically importing我应用中的 CSS:

// app.js
class App extends React.Component {
  // constructor

  login(themeName) {
    import(/* webpackChunkName: "`${themeName}`" */ `./path/to/${themeName}.scss`).then(theme => {
      // do something with `theme`
    }
  }

  // other stuff
}

我需要能够在 login() 中动态加载该 css 文件,我只是不确定当它生成了 [contenthash] 时如何引用它>.

TLDR:有没有一种好的方法既可以提取 css 又可以将引用的 CSS 包导入到以后的延迟加载中?我不受限于 mini-css-extract-plugin

编辑:创建了一个 mini-css-extract-plugin 问题 here .

最佳答案

我的解决方案最终使用了 extract-text-webpack-plugin .我的配置现在看起来像这样:

// webpack.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ExtractThemeA = new ExtractTextPlugin({ filename: 'themeA.[hash].css', allChunks: true});

module.exports = {
  plugins: [
      ExtractThemeA,
      // more plugins for other css files
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        // Note: No changes to splitChunks
        'vendor': {
            // custom commons chunk for js
        }
    }
  }
  module: {
    rules: [
      {
        test: /theme-a\.scss$/,
        use: ExtractThemeA.extract([ 'css-loader', 'sass-loader' ])
      },
      // more module rules for each css file needed
    ]
  }
}

然后,这些 block 在我的 HtmlWebpackPlugin 中通过文件名可用:

<!-- HtmlWebpackPlugin Template -->
<script>
// provides me with an array of file name strings
var themesManifest = <%= htmlWebpackPlugin.files.css %>
</script>

关于css - 从 SCSS 中提取 CSS 并在 React 应用程序中延迟延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935614/

相关文章:

html - CSS - HTML 文本突出显示了不应该出现的位置

javascript - 启用带有情感的全局主题?

reactjs - Electron :无法加载 http://localhost:8080

javascript - 为什么我们应该使用 import React from 'react'

javascript - 使用 React、TypeScript 和 HMR 的工作 WebPack 设置

node.js - Webpack2 热模块重新加载 Express.js 通用 React 应用程序

javascript - 如何使用 webpack 连接和缩小文件

javascript - 从悬停到点击的下拉菜单

css - 在右侧显示引导下拉菜单

css - 将涉及多个元素的条目添加到 CKEDITOR.stylesSet