在 Nextjs 中编辑 CSS-loader 的 localIdentName 以对用户隐藏类名 [英] Edit CSS-loader's localIdentName in Nextjs to hide class names from users

查看:118
本文介绍了在 Nextjs 中编辑 CSS-loader 的 localIdentName 以对用户隐藏类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Nextjs 的 Webpack 配置中编辑 css-loaderlocalIdentName 字段,以便我可以散列/隐藏/混淆 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.

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

If you are using Webpack 5 or (Next.js 10.2 or a newer version) Use this code:

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, { 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-loader 的 localIdentName 以对用户隐藏类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆