在 Nextjs 中编辑 CSS-loader 的 localIdentName 以对用户隐藏类名

问题描述

如何在 Nextjs 的 Webpack 配置中编辑 localIdentNamecss-loader 字段,以便我可以散列/隐藏/混淆 css 类名称?

以下示例来自《纽约时报》。注意类名:

enter image description here

解决方法

遗憾的是,Nextjs 中没有内置支持将自定义配置传递给 Webpack 加载器。但是我们可以通过使用 next.config.js 来解决这个问题。

首先,在项目目录的根目录中创建 next.config.js

如果您使用的是 Webpack 5 或(Next.js 10.2 或更新版本),请使用以下代码:

module.exports = {
  webpack(config,{ buildId,dev,isServer,defaultLoaders,webpack }) {
    config.module.rules[2].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,webpack }) {
    config.module.rules[1].oneOf.forEach((moduleLoader,};

如果您想仅在生产中散列类名称,您可以将 process.env.NODE_ENVif 语句一起使用。像这样:

module.exports = {
  webpack(config,webpack }) {
    if (process.env.NODE_ENV === "production") {
      ...
      ...

      return config;
    } else {
      return config;
    }
  },};
,

这对我使用 Next.js 11 很有效:

module.exports = {
        webpack: (config,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,};
              }
            });
        });
          return config;
      },};

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...