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

前端之家收集整理的这篇文章主要介绍了从SCSS中提取CSS并在React应用程序中延迟延迟加载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些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.

解决方法

对不起我的理解,

你可能只需制作两个不同的scss文件并根据需要导入它们. theme.scss admin.scss或者像这样

这就是我现在在React中做scss的方法

在App.js中

import styles from '../../stylesheet/main.scss'
// could be as well
import styles1 from '../../stylesheet/theme.scss' // some file
import styles2 from '../../stylesheet/admin.scss' // some other file

const App = () => {
  <div className={styles.action_Feed} >{ content }</div>
}

在main.scss中

.action_Feed {
  position: fixed;
  width: 350px;
  height: auto;
  max-height: 100%;
  max-width: 100%;
  top: 0;
  left: 0;
  z-index: 9999;
}

我想你也可以这样做

const themeName = 'main'
import(`./stylesheet/${themeName}.scss`,(css) => {
  // meaby set this to state? not quite sure how should properly handle
  // dynamically imported css
  this.setState({ css: css.action_Feed })

  // or possible this way. I have done some non-React dom manipulation
  // this way before
  document.querySelector('body').classList.add(css.action_Feed)
})

<div className={this.state.css}>{ content }</div>

你应该查看React的新Refs API.它可能会给你一些很好的灵活性,可以将className-attr赋予所需的元素.

设置为splitChunks.chunks到所有的工作虽然我想在这种情况下无论如何

原文链接:https://www.f2er.com/css/242197.html

猜你在找的CSS相关文章