Code Monkey home page Code Monkey logo

webpack2-quickstart's Introduction

웹팩2 가볍게 시작하기

1. 패키지 설정

init

$ npm init

웹팩을 설치합니다.

웹팩은 2 버전 마지막 버전인 2.6.1 로 설치하겠습니다.

$ npm install [email protected] --save-dev

웹팩 개발 서버를 설치합니다.

$ npm install webpack-dev-server --save-dev

html-webpack-plugin 플러그인 설치

$ npm install html-webpack-plugin --save-dev

// 예시
// package.json
{
  "name": "cheolguso-webpack2",
  "version": "1.0.0",
  "description": "웹팩2 연습",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "CHEOLGUSO",
  "license": "WTFPL",
  "devDependencies": {
    "html-webpack-plugin": "^2.30.1",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.11.1"
  }
}

2. 웹팩 설정

index.html 생성

$ vi index.html
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>cheolguso : webpack version2 guide</title>
  </head>
  <body>
    hello
  </body>
</html>

index.js 생성

$ vi index.js
document.write(' world');

webpack.config.js 생성

$ vi webpack.config.js
'use strict';

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = function makeWebpackConfig() {
  var config = {};
  
  config.entry = {
    app: './index.js',
  };

  config.output = {
    path: __dirname + '/build',
    filename: 'cheolguso.bundle.js'
  };

  config.devtool = 'eval-source-map';

  config.module = {};

  config.plugins = [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({
      template: './index.html',
      inject: 'body'
    })
  ];

  return config;
}();

3. npm 커맨드 수정 및 실행

package.json 수정

// package.json
{
  "name": "cheolguso-webpack2",
  "version": "1.0.0",
  "description": "webpack version2 guide",
  "main": "index.js",
  "scripts": {
    "build": "webpack --bail --progress --profile",
    "server": "webpack-dev-server --history-api-fallback --inline --progress"
  },
  "author": "CHEOLGUSO",
  "license": "WTFPL",
  "devDependencies": {
    "html-webpack-plugin": "^2.30.1",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.11.1"
  }
}

개발 서버 실행

$ npm run server

빌드

$ npm run build

4. 웹팹 설정에 관한 간단한 설명

entry, output

위 예제에서는 이부분 입니다.

...
config.entry = {
  app: './index.js',
};

config.output = {
  path: __dirname + '/build',
  filename: 'cheolguso.bundle.js'
};
...

entry는 몇가지 형태로 존재하는데, 그 이해를 위해선 output도 함께 보는 것이 좋습니다.

// 1.
config.entry = './index.js';
config.output = {
  path: __dirname + '/build',
  filename: 'cheolguso.bundle.js'
}
// 2.
config.entry = ['./index.js', './addScript.js'];
config.output = {
  path: __dirname + '/build',
  filename: 'cheolguso.bundle.js'
}
// 3.
config.entry = {
  index : './index.js', 
  addScript : './addScript.js'
};
config.output = {
  path: __dirname + '/build',
  filename: '[name].bundle.js'
}
// 여기에서 [name]은 entry객체의 키값이 됩니다. (eg. index, addScript)

devtool

config.devtool = 'eval-source-map';

압축, 난독화, es6+ 의 트랜스파일 등의 작업들로 어려워지는 디버깅을 소스맵을 통해 조금 수월하게 할 수 있는 옵션으로 이미 여러가지 옵션이 있으며 플러그인을 통해 더 확장되는 것으로 보입니다.
몇가지 대표적인 옵션에 대한 성능 태스트는 아래의 링크에서 잘 되어 있는 것 같습니다.

참고링크 : https://perfectacle.github.io

개인적으로는 angular1 + babel을 사용한 프로젝트에서 eval 이 포함되지 않는 옵션은 알 수 없는 오류가 발생해서 실험해보지 못하였으며, 단순히 결과적으로 배포를 위한 번들을 만듦에 있어, eval-source-map 에서 2.7mb 였던 번들의 크기가 eval에서 830kb 로 줄어드는 것을 알 수 있었습니다.

아직 정확한 옵션 하나 하나의 정확한 차이는 알 지 못합니다. 이후에 추가 작성할 예정입니다.

module

config.module = {
  rules: [{
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      query: {
        presets: ['es2015']
      }
    }
  }, {
    test: /\.less$/,
    use: [
      {loader: "style-loader"},
      {loader: "css-loader", options: {sourceMap: true}},
      {loader: "less-loader", options: {sourceMap: true}}
    ]
  }]
};

예를 들어 위와 같이 설정한다면, es6 -> es5로 less는 css 트랜스파일됩니다.

babel-loader, style-loader, css-loader, less-loader 는 별도 설치

참고링크 : https://webpack.js.org/configuration/module/

plugins

config.plugins = [
  new webpack.optimize.UglifyJsPlugin()
];

이름 그대로 플러그인을 설정합니다.
UglifyJsPlugin 플러그인은 자바스크립트 코드를 압축해줍니다.

참고링크 : https://webpack.js.org/configuration/plugins/

5. 마무리

인터넷 속에서 수 많은 글들을 참고하였지만, 그 중 몇가지 좋은 글을 링크로 남깁니다.

webpack2-quickstart's People

Contributors

falsy avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.