Css 如何设置next.config.js使类名只包含哈希?
我使用next.js和css模块。节点sass和@zeit/next sass我不想使用。您能告诉我们如何配置next.config.js,使类名只包含散列吗? package.json:Css 如何设置next.config.js使类名只包含哈希?,css,webpack,next.js,Css,Webpack,Next.js,我使用next.js和css模块。节点sass和@zeit/next sass我不想使用。您能告诉我们如何配置next.config.js,使类名只包含散列吗? package.json: { "name": "learn-starter", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next s
{
"name": "learn-starter",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "9.3.5",
"react": "16.13.1",
"react-dom": "16.13.1",
"sass": "^1.26.8"
}
}
要实现只包含哈希的类名,您必须遵循以下css文件的命名约定 Next.js支持使用[name].module.CSS文件命名约定的CSS模块。参考下面的示例 首先,使用以下内容创建组件/Button.module.css:
.error {
color: white;
background-color: red;
}
然后,创建components/Button.js,导入并使用上述CSS文件:
import styles from './Button.module.css'
export function Button() {
return (
<button
type="button"
// Note how the "error" class is accessed as a property on the imported
// `styles` object.
className={styles.error}
>
Destroy
</button>
)
}
从“./Button.module.css”导入样式
导出功能按钮(){
返回(
毁灭
)
}
CSS模块是可选功能,仅对扩展名为.module.CSS的文件启用
但是,您可能会看到只包含哈希的类名;当您运行生产构建(npm运行构建)时,对于开发构建(npm启动),它可能不会执行完整的仅哈希名称。解决方案:
const regexEqual = (x, y) =>
x instanceof RegExp &&
y instanceof RegExp &&
x.source === y.source &&
x.global === y.global &&
x.ignoreCase === y.ignoreCase &&
x.multiline === y.multiline;
module.exports = {
webpack(config) {
const sassRules = config.module.rules
.find((rule) => typeof rule.oneOf === "object")
.oneOf.find(
(rule) =>
rule.sideEffects === false &&
regexEqual(rule.test, /\.module\.(scss|sass)$/)
);
sassRules.use = sassRules.use.map((rule) =>
rule.loader.includes("css-loader/dist")
? {
...rule,
options: {
...rule.options,
modules: {
...rule.modules,
localIdentName: "[hash:base64:5]",
},
},
}
: rule
);
return config;
},
};
第5页: