我有一个包含多个反应组件的仓库,这些组件需要彼此完全分开工作,因此每个组件都有自己的输出目录,其中包含各自的 CSS、JS 和 HTML。为了实现这一点,我迭代了一个包含所有组件名称的数组,添加了入口点、HTMLWebpackPlugin、SASS 和 CSS 加载器以及提取文本插件,每个都带有组件的路径。
config = { /*...someGlobalWebpackSettings like alias, externals etc. */ }
components.forEach(component => {
const extractStyles = new ExtractTextPlugin({ allChunks: true, filename: `${component}/${component}.css` })
const componentPath = path.resolve(base, 'src', 'components', component)
config.entry[component] = componentPath
config.plugins.push(extractStyles)
config.plugins.push(new HtmlWebpackPlugin({
filename: path.resolve(base, 'dist', `${component}/${component}.html`),
chunks: [component],
template: path.resolve(base, 'index.html')
}))
config.module.rules.push({
test: /\.scss$/,
exclude: /node_modules/,
include: [componentPath],
use: extractStyles.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
})
config.module.rules.push({
test: /\.css$/,
include: [componentPath, ...publicStylePaths],
use: extractStyles.extract({
fallback: "style-loader",
use: ["css-loader"]
})
})
})
这仅适用于一个组件,但由于某种原因,当添加第二个组件时,第一个组件的样式会消失,这意味着相应的 CSS 文件只有全局样式,而不是组件特定的样式。这可能与 ExtractText 插件无法与多个实例一起正常工作有关,但我真的不确定。
查看 webpack 构建输出,您可以看到,第二个 css 文件要小得多,因为它只有全局样式。让我恼火的是,两个 css 文件都列出了两个组件块,这是什么意思?
这里有没有人对此有适当的解决方案或试图实现类似的目标?他们是我不知道的明显方式吗?提前非常感谢!