【发布时间】:2018-09-30 19:33:59
【问题描述】:
我有一些 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。
【问题讨论】:
标签: css reactjs webpack lazy-loading