LoginSignup
2
4

More than 5 years have passed since last update.

angular-cliで作成したプロジェクトで--prodビルド時にconsole.log出力を削除する

Posted at

開発時には重宝するconsole.logですが、リリースビルド時には綺麗サッパリ消えてほしいものです。
loggerクラスを用意して、console.logの出力の有無を制御する方法もありますが、今回はビルド時に一気に無効、削除する方法を試してみました。

前提

$ ng -v
@angular/cli: 1.4.1
node: 8.1.3

手順

console.logをオーバーライドする方法

console.logを何もしない関数にオーバーライドする方法です。

main.tsに以下の記述を追加します。

main.ts
if (environment.production) {
  window.console.log = function(){};
}

ここで、ng build --prodでビルドして実行結果を確認すると、全てのconsole.logでの出力が出力されなくなっています。

strip-loaderを使う方法

webpackのローダーを使って、特定の文字列(コード)をビルド時に削除する方法です。

strip-loader

プロジェクトのルートディレクトリで、ng ejectコマンドを実行してwebpack.config.jsを取り出します。

$ ng eject
==========================================================================================
Ejection was successful.

To run your builds, you now need to do the following commands:
   - "npm run build" to build.
   - "npm test" to run unit tests.
   - "npm start" to serve the app using webpack-dev-server.
   - "npm run e2e" to run protractor.

Running the equivalent CLI commands will result in an error.

==========================================================================================
Some packages were added. Please run "npm install".

このタイミングで、webpack-dev-serverやwebpackなどのパッケージが追加されてるので、
npm installを実行しておきます。

strip-loaderをインストールします。

$ npm install --save-dev strip-loader

webpack.config.js を修正し、strip-loaderを使用するように設定します。

webpack.config.js
...
  "module": {
    "rules": [
      {
        "enforce": "pre",
        "test": /\.js$/,
-        "loader": "source-map-loader",
+        "loader": ["source-map-loader", "strip-loader?strip[]=console.log"],
        "exclude": [
          /(\\|\/)node_modules(\\|\/)/
        ]
      },

ここで、npm run build --prod(ng ~系のスタート、ビルドコマンドは使用できなくなってるので)でビルドして実行結果を確認すると、全てのconsole.logでの出力が出力されなくなっています。

所感

angular-cliでwebpackの設定を変更するのはつらい。

参考

angular-cli でwebpack の設定を変更する方法が参考になりました
https://qiita.com/kaku3/items/a15f67e97f35e35611df

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4