-->

[Webpack] Webpack 기초

 

 

ECMA2015부터 javascript 문법 수준에서 Module을 지원하기 시작했다.

module을 구현하는 대표적인 스펙이 AMD(Asynchronous Module Definition)와 CommonJS인데 Node.js가 바로 이 CommonJS를 사용한다. 

UMD(Universal Module Definition)는 AMD 기반으로 CommonJS 방식까지 지원하는 통합 형태이다.

이렇게 각 커뮤니티에서 각자의 스펙을 제시하다가 ES2015에서 표준 모듈 시스템을 내놓았다.

현재는 Webpack과 Babel을 이용해 모듈 시스템을 사용하는 것이 일반적이다.

import/export를 사용하지 않고 코딩해왔으나 앞으로는 최신 javascript문법을 사용하는 Frontend framework이나 Node.js를 제대로 사용하려면 module 활용이 필수적이다.

 

Webpack은 여러개 파일을 하나의 파일로 합쳐주는 번들러(Bundler)이다. 번들러의 종류도 여러 가지가 있지만 Webpack이 사실상 최강자 타이틀을 갖고 있다.

여기서 Entry/Output이라는 개념이 나오는데 이는 하나의 시작점을 의미하고, 이 Entry부터 의존적인 모듈을 전부 찾아내서 하나의 Output을 만들어낸다.

 

간단히 Webpack으로 번들링 작업을 해보자.

 

1. Node.js & NPM 버전 체크

$ node -v
v16.14.2

$ npm -v
8.5.0

당연히 node.js가 설치 되어있어야 한다.

 

2. 프로젝트 생성

2-1. npm init

$ mkdir webpack-sample && cd $_
$ npm init                                                                      
This utility will walk you through creating a package.json file.           
It only covers the most common items, and tries to guess sensible defaults.
                                                                           
See `npm help init` for definitive documentation on these fields           
and exactly what they do.                                                  
                                                                           
Use `npm install <pkg>` afterwards to install a package and                
save it as a dependency in the package.json file.                          
                                                                           
Press ^C at any time to quit.                                              
package name: (webpack-sample)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\IntelliJ IDEA 2022.1\workspace\FE\webpack-sample\package.json:

{
  "name": "webpack-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes)

 

2-2.npm install react

$ npm install react

added 3 packages, and audited 4 packages in 712ms

found 0 vulnerabilities

 

2-3.npm install -D webpack webpack-cli

$ npm install -D webpack webpack-cli

added 117 packages, and audited 121 packages in 6s

15 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

 

 

 

3. 소스 생성

source tree

D:\IntelliJ IDEA 2022.1\workspace\FE\webpack-sample
├── index.html
├── node_modules
├── package-lock.json
├── package.json
└── src
   ├── app.js
   └── math.js

 

package.json

{
  "name": "webpack-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^18.2.0"
  },
  "devDependencies": {
    "webpack": "^5.73.0",
    "webpack-cli": "^4.10.0"
  }
}

 

math.js

export function sum(a,b){
    return a+b;
}

 

app.js

import * as math from './math.js';

console.log(math.sum(2,4));

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--    <script type="module" src="src/app.js"></script>-->
    <script src="dist/main.js"></script>
</body>
</html>

 

4. webpack 실행

$ node_modules/.bin/webpack --mode development --entry ./src/app.js
asset main.js 4.09 KiB [emitted] (name: main)
runtime modules 670 bytes 3 modules
cacheable modules 111 bytes
  ./src/app.js 65 bytes [built] [code generated]
  ./src/math.js 46 bytes [built] [code generated]
webpack 5.73.0 compiled successfully in 94 ms

dist폴더가 생성되고 소스가 번들링되어 나온다.

 

5. 확인

$ npx lite-server
Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
** browser-sync config **
{
  injectChanges: false,
  files: [ './**/*.{html,htm,css,js}' ],
  watchOptions: { ignored: 'node_modules' },
  server: {
    baseDir: './',
    middleware: [ [Function (anonymous)], [Function (anonymous)] ]
  }
}
[Browsersync] Access URLs:
 -------------------------------------
       Local: http://localhost:3000
    External: http://192.168.56.1:3000
 -------------------------------------
          UI: http://localhost:3001
 UI External: http://localhost:3001
 -------------------------------------
[Browsersync] Serving files from: ./
[Browsersync] Watching files...
22.07.03 15:59:40 200 GET /index.html
22.07.03 15:59:40 200 GET /dist/main.js

npx lite-server를 이용해 로컬에서 바로 띄워본다. 

 

6. webpack.config.js

const path = require('path');

module.exports = {
    mode: 'development',
    entry:{
        main: './src/app.js',
    },
    output: {
        path: path.resolve('./dist'),
    filename: '[name].js'
    }
}

폴더 최상단에 webpack환경설정 파일을 만들고 npm build 명령어를 이용해 간단히 실행할 수 있다.

$ npm run build

> webpack-sample@1.0.0 build
> webpack

asset main.js 4.09 KiB [compared for emit] (name: main)
runtime modules 670 bytes 3 modules
cacheable modules 111 bytes
  ./src/app.js 65 bytes [built] [code generated]
  ./src/math.js 46 bytes [built] [code generated]
webpack 5.73.0 compiled successfully in 113 ms

 

 

https://github.com/minha9012/webpack-sample

 

GitHub - minha9012/webpack-sample

Contribute to minha9012/webpack-sample development by creating an account on GitHub.

github.com

 

+ Recent posts