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

时间:2018-04-20 06:45:36

标签: 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

2 个答案:

答案 0 :(得分:5)

我的解决方案最终使用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
    ]
  }
}

然后,我的HtmlWebpackPlugin中的文件名可以使用这些块:

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

答案 1 :(得分:4)

对不起我的理解,

你可能只需制作两个不同的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.chunksall虽然我认为无论如何都可以使用