我使用css-loader
.
最后,我可以使用postcss-modules和posthtml-css-modules
首先,postcss-modules
将 .css/.scss 文件转换为 base64 中的哈希。此外,它会.json
为每个 .css/.scss 文件创建文件,其中包含每个类名到其对应哈希名的映射。
然后,posthtml-css-modules
获取使用 .css/.scss 文件的 html 文件,并将使用名为 with 的类的 html 元素转换为在 .css 中css-modules
定义的相应哈希名称.json
。
webpack.config.js:
module.exports = function (options) {
...
return {
...
module: {
rules: [
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
loader: '@ngtools/webpack'
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader'
},
{
loader: 'posthtml-loader',
options: {
config: {
ctx: {
include: {...options},
content: {...options}
}
}
}
}
],
exclude: [helpers.root('src/index.html')]
},
{
test: /\.(css|sass|scss)$/,
exclude: [helpers.root('src', 'styles')],
use: [
'to-string-loader',
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.(jpg|png|gif|svg)$/,
loader: 'file-loader',
options: {
name: 'assets/[name].[hash].[ext]',
}
},
{
test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
use: 'file-loader'
}
],
},
};
};
postcss.config.js
module.exports = {
plugins: [
require('autoprefixer'),
require("postcss-modules")({
generateScopedName: "[hash:base64:5]"
})
]
}
posthtml.config.js
module.exports = ({ file, options, env }) => ({
plugins: [
require('posthtml-css-modules')(file.dirname.concat('/').concat(file.basename.replace('.html','.scss.json')))
]
});