I had the same issue using css-loader
.
At the end, I could do it using postcss-modules and posthtml-css-modules
First, postcss-modules
convert the .css/.scss files to hash in base64. Also, it creates .json
file per each .css/.scss file where it contains the mapping for each class name to his corresponding hash name.
Then, posthtml-css-modules
takes the html files where you use the .css/.scss files and convert the html elements that uses the classes named with css-modules
to his corresponding hash name defined in the .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')))
]
});