如何在 Nextjs 中散列 CSS 类名? [英] How to hash CSS class names in Nextjs?
问题描述
如何在 Nextjs 的 Webpack 配置中编辑 css-loader
的 localIdentName
字段,以便我可以散列/隐藏/混淆 css 类名?
How can I edit localIdentName
field of css-loader
in Webpack configuration in Nextjs so that I can hash/hide/obfuscate css class names?
下面的例子来自纽约时报.注意类名:
The example below is from the New York Times. Note the class names:
推荐答案
不幸的是,Nextjs
中没有内置支持将自定义配置传递给 Webpack
加载器.但是我们可以通过使用 next.config.js
来解决它.
Unfortunately there is no build in support in Nextjs
to pass custom configuration to Webpack
loaders. But we can work around it by using next.config.js
.
首先,在项目目录的根目录中创建 next.config.js
.
First, create next.config.js
in the root of your project directory.
对于 Nextjs 11
module.exports = {
webpack(config, { buildId, dev, isServer, defaultLoaders, webpack }) {
config.module.rules[3].oneOf.forEach((moduleLoader, i) => {
Array.isArray(moduleLoader.use) &&
moduleLoader.use.forEach((l) => {
if (
l.loader.includes("\\css-loader") &&
!l.loader.includes("postcss-loader")
) {
const { getLocalIdent, ...others } = l.options.modules;
l.options = {
...l.options,
modules: {
...others,
localIdentName: "[hash:base64:6]",
},
};
}
});
});
return config;
},
};
对于 Next.js 10.2 或更新版本:
module.exports = {
webpack(config, { buildId, dev, isServer, defaultLoaders, webpack }) {
config.module.rules[3].oneOf.forEach((moduleLoader, i) => {
Array.isArray(moduleLoader.use) &&
moduleLoader.use.forEach((l) => {
if (
l.loader.includes("\\css-loader") &&
!l.loader.includes("postcss-loader")
) {
const { getLocalIdent, ...others } = l.options.modules;
l.options = {
...l.options,
modules: {
...others,
localIdentName: "[hash:base64:6]",
},
};
}
});
});
return config;
},
};
否则使用此:
module.exports = {
webpack(config, { buildId, dev, isServer, defaultLoaders, webpack }) {
config.module.rules[1].oneOf.forEach((moduleLoader, i) => {
Array.isArray(moduleLoader.use) &&
moduleLoader.use.forEach((l) => {
if (
l.loader.includes('\\css-loader') &&
!l.loader.includes('postcss-loader')
) {
const { getLocalIdent, ...others } = l.options.modules;
l.options = {
...l.options,
modules: {
...others,
localIdentName: '[hash:base64:6]',
},
};
}
});
});
return config;
},
};
如果您想仅在生产中散列类名称,您可以使用带有 if
语句的 process.env.NODE_ENV
.像这样:
If you want to hash the class names only in production, you can use process.env.NODE_ENV
with an if
statement. Like this:
module.exports = {
webpack(config, { buildId, dev, isServer, defaultLoaders, webpack }) {
if (process.env.NODE_ENV === "production") {
...
...
return config;
} else {
return config;
}
},
};
这篇关于如何在 Nextjs 中散列 CSS 类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!