如何在Nextjs中散列CSS类名?
如何在 Nextjs 中编辑Webpack 配置中的localIdentName字段,css-loader以便我可以散列/隐藏/混淆 css 类名?
下面的例子来自纽约时报。注意类名:
回答
不幸的是,没有内置支持Nextjs将自定义配置传递给Webpack加载程序。但是我们可以通过使用next.config.js.
首先,next.config.js在项目目录的根目录中创建。
对于 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;
},
};
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[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;
},
};
如果只想在 production 中散列类名,则可以使用process.env.NODE_ENVwithif语句。像这样:
module.exports = {
webpack(config, { buildId, dev, isServer, defaultLoaders, webpack }) {
if (process.env.NODE_ENV === "production") {
...
...
return config;
} else {
return config;
}
},
};