21세기 프론트엔드 (3) 배포하기

in #front-end7 years ago

이전 글에서 기본적인 개발환경을 세팅했습니다. 이제 프로그램을 완성했다고 가정하고, 완성된 코드와 디렉토리를 서버에 올릴 수 있는 배포용으로 가공하는 방법을 살펴보겠습니다.

UglifyJS 사용하기

코드가 길어질 경우 번들링된 bundle.js 파일이 엄청나게 커질 수 있습니다. 그래서 코드를 압축하는 과정이 필요한데, 이때 사용하는 것이 UglifyJS입니다. 이와 같은 압축기(compressor)에는 YUI CompressorGoogle Closure Compiler가 있습니다. 이러한 압축기는 코드의 변수명도 모두 한 글자 정도로 바꿔주기 때문에 압축과 난독화의 기능을 동시에 합니다. 우리는 webpack의 플러그인으로 만들어진 UglifyJS를 사용할 것입니다. npm을 통해 설치해주세요.

npm install uglifyjs-webpack-plugin --save-dev

그리고 webpack.config.js을 수정해 이 플러그인을 적용해줍니다.

// webpack.config.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './',
    compress: true,
    port: 9000
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }, 
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ]
  },
  plugins: [
    new UglifyJsPlugin()
  ],
};

자, 이제 터미널에서 npm run build를 실행하면 UglifyJS를 거쳐 압축된 번들 코드가 만들어지는 것을 볼 수 있습니다!

CopyWebpackPlugin 사용하기

지금까지 하나의 폴더에서 모든 파일을 관리해왔는데요, 실제로 프로젝트의 규모가 커지면 단일 폴더에서 파일을 관리하기는 쉽지 않습니다. 그래서 아래와 같이 폴더를 쪼개개됩니다.

.
├── dist/
│   └── index.html
│   └── css/
│       └── index.css
│   └── js/
│       └── bundle.js
├── public/
│   └── index.html
│   └── css/
│       └── index.css
├── src/
│   └── index.js
├── node_modules/
│   └── ...
├── package.json
└── webpack.config.js

이건 제가 주로 사용하는 디렉토리 구조이고, 사용하는 프레임워크나 언어, 환경에 따라 디렉토리 구조는 바뀔 수 있습니다. (Vue.js의 경우 이런 식의 디렉토리 구조를 제안합니다.) dist는 배포파일을, public은 html/css와 같은 static 파일을, src는 자바스크립트 파일을 담는 폴더로 구성하고 있습니다. public이나 src 폴더는 개발환경에서 사용하고, 실제 서버에 올리거나 사용자에게 배포되는 코드는 dist에 모아둡니다. 물론 파일을 직접 손으로 옮기진 않고, CopyWebpackPlugin이라는 웹팩 플러그인을 사용합니다.

npm install copy-webpack-plugin

플러그인을 설치한 뒤에는 역시 webpack.config.js를 수정해줍니다.

// webpack.config.js
const CopyWebpackPlugin = require('copy-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './index.js',
  output: {
    path: './dist/src/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist/',
    compress: true,
    port: 9000
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }, 
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ]
  },
  plugins: [
    new UglifyJsPlugin(),
    new CopyWebpackPlugin([{
      from: './public/',
      to: './dist/'
    }]),
  ],
};

bundle.js가 아웃풋되는 path를 바꿔서 dist 폴더 아래 src 폴더에 자동으로 넣도록했고, CopyWebpackPlugin은 public 폴더의 파일들을 dist 폴더에 넣도록 설정했습니다. 이제 빌드를 하면 자동으로 dist 폴더에 src 폴더, css 폴더, js 폴더가 생기면서 배포용 파일들을 모아주게 됩니다. devServer의 contentBase 값도 ./dist/로 바꿔줍니다.

기본 튜토리얼은 끝났습니다! 앞으로는 ESLint나 Sass처럼 개발을 더욱 편리하게 만들어주는 도구들과 프레임워크들에 대해 다뤄보도록 하겠습니다.

Sort:  

Congratulations @caesium133! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @caesium133! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 58039.01
ETH 2460.08
USDT 1.00
SBD 2.32