如何与 CSS 模块一起使用
PurgeCSS 通过比较内容文件中的选择器与 CSS 文件中的选择器来工作。当使用 CSS 模块时,你的类名将被哈希替换。因此,使用 CSS 模块和 PurgeCSS 可能不像你希望的那么简单。
以下是使用 CSS 模块和 React 的 PurgeCSS 方法。该项目是使用 create-react-app 创建的。然后,运行 npm run eject
将其弹出。
const glob = require('glob-all');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
const shouldUseRelativeAssetPaths = publicPath === './';
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {}
},
{
loader: require.resolve('css-loader'),
options: cssOptions
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
syntax: 'postcss-scss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
}),
require('@fullhuman/postcss-purgecss')({
content: [ paths.appHtml, ...glob.sync(path.join(paths.appSrc, '/**/*.{js,jsx}'), { nodir: true }) ],
}),
require('postcss-normalize')
].filter(Boolean),
sourceMap: isEnvProduction && shouldUseSourceMap
}
}
].filter(Boolean);
if (preProcessor) {
loaders.push({
loader: require.resolve(preProcessor),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap
}
});
}
return loaders;
};
return {
/* {...} */
module: {
rules: [
/* {...} */
{
oneOf: [
/* {...} */
{
test: /\.module\.(scss|sass)$/,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent
},
'sass-loader'
)
}
/* {...} */
]
}
/* {...} */
]
},
/* {...} */
};
};
你可以在 JSX 中使用常规模块语法,如下所示
// @flow
import styles from './Test.module.scss';
import * as React from 'react';
type Props = {};
type State = {};
export default class Test extends React.Component<Props, State> {
render(): * {
return (
<div className={styles.myCssClass}></div>
);
}
}