# nextjs のproduction環境でだけconsoleを出力しないようにする

3 min read
Table of Contents

結論

/** @type {import('next').NextConfig} */
const nextConfig = {
// Error: "next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.
// output: "export",
reactStrictMode: false,
compiler: {
removeConsole: process.env.NODE_ENV === "production",
},
};
export default nextConfig;

上記コードでnextjsproduction ビルド時にconsoleが出力されなくなる。にした。

デバッグしないと進めない

コードを見て何が起きいるのかわかるくらいの玄人であれば問題ないんだけど、そんな技術力はなく、consoleを出しまくり、どこで何がどうなっているのかを確認しないと進めない。

そんな具合なのでコンソール画面には大量のログが溢れる。

当然そんな状況じゃ、デプロイできないので、いちいちconsoleを消すのは面倒だし、そのまま開発環境ではconsoleを使いたい。

なので、デプロイ時だけ消したい。

本番環境でだけconsoleを消したい

nextjsでは設定でデプロイ時だけconsoleを出力しない方法があるので実行した。

てかたぶん、ほとんどのフレームワークにはあると思うんだけど。

next.config.jsで下記設定をする。

module.exports = {
compiler: {
removeConsole: process.env.NODE_ENV === "production",
},
};

NODE_ENVを自身で定義する必要があると思ったけど、

公式を参照すると、

The greater React ecosystem treats NODE_ENV as a convention, only permitting three (3) values:

production: When your application```` is built with next build development: When your application is run with next dev test: When your application is being tested (e.g. jest)

のように事前に定義されているっぽい。

これでどんどんconsoleを出力できる。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments