본문 바로가기
VueJS/NuxtJS

[NuxtJS] 빌드/운영 배포 시 console.log 제거하기

by 썸머워즈 2023. 1. 14.
반응형

NuxtJS 빌드 시 console 제거하기

개발을 하다 보면 console.log를 쓰면서 확인을 해야 하는 경우가 많은데,

배포를 하면서 미처 지우지 못한 console.log의 잔해들이 남을 수 있다.

 

그럴 때 사용할 수 있는 두 가지 방법에 대해 기록해 둔다.

아 물론 이 방법들이 NuxtJS뿐만 아니라 다른 곳에서도 사용이 가능할 것으로 보이니 알아두면 좋을 것 같다.


1.babel-plugin-transform-remove-console

babel의 플러그인을 사용하여 console을 지우는 방법이 존재한다.

npm install --save-dev babel-plugin-transform-remove-console
yarn add --dev babel-plugin-transform-remove-console

플러그인을 우선 설치를 해주고

nuxt.config.js 파일에 들어가 아래와 같이 수정해서 사용하면 된다.

 

▷ nuxt.config.js

export default {
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    babel: {
      // plugins: [['transform-remove-console', { "exclude": [ "warn" ] }]],
      plugins: [['transform-remove-console']]
    }
  }
}

특정 console은 지우지 않고 제외하고 싶다면 위 코드에서 주석처리한 것처럼 옵션을 추가해 주면 된다.


2.terser 사용

terser는 NuxtJS의 경우 프로젝트를 생성하면 자동으로 들어가 있기 때문에 따로 설치해 줄 필요는 없다.

그래서 그 terser의 옵션을 사용하게 되면 production build에서 console이 사라지게 된다.

 

▷ nuxt.config.js

export default {
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    terser: {
      // https://github.com/terser/terser#compress-options
      terserOptions: {
        compress: {
          drop_console: true
        }
      }
    }
  }
}

위에서 설명한 production build는 실제 운영 배포할 때 사용되는 빌드라고 생각하면 된다.

프로젝트를 생성하게 되면 Readme에도 다음과 같이 적혀 있으니 참고하면 좋을 것 같다

# install dependencies
$ yarn install

# serve with hot reload at localhost:3000
$ yarn dev

# build for production and launch server
$ yarn build
$ yarn start

# generate static project
$ yarn generate

우선 두 가지 방법을 설명하였는데, NuxtJS뿐만 아니라 다른 곳에서도 충분히 사용이 가능해 보인다.

 

두 플러그인의 차이점은

babel-plugin-transform-remove-console의 경우 그냥 개발, 운영 배포 가릴 거 없이 그냥 지워버리는 반면에,

terser의 경우에는 운영 배포 시에만 사라진다.

물론 상세 옵션이 따로 있을 수는 있지만 당장 저렇게 사용하게 되면 저런 식의 효과를 가지고 있다.

 

그리고 terser의 경우 보통 대부분 내장되어 있는 경우가 많아서 따로 설치해 줄 필요가 없으니 나는 첫 번째 방법보다는 두 번째 방법이 더 좋아 보인다.


참고: https://stackoverflow.com/questions/64409416/nuxtjs-disable-console-log-in-production-env

 

NuxtJS: Disable console.log in production env

I am looking for a way to disable console.log() for production env. Something like putting the below code to nuxt.config.js or index.js: if (process.env.NODE_ENV !== "development") { c...

stackoverflow.com

참고: https://nuxtjs.org/docs/configuration-glossary/configuration-build/#terser

 

The build Property

Nuxt lets you customize the webpack configuration for building your web application as you want.

nuxtjs.org

참고: https://webpack.js.org/plugins/terser-webpack-plugin/

 

TerserWebpackPlugin | webpack

webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

webpack.js.org

반응형


댓글

TOP