rollup.js 를 이용한

자바스크립트 번들러 이해하기

Lead Software Engineer @NHN Dooray (2021~)

Lead Software Engineer @ProtoPie (2016 ~ 2021)

Microsoft MVP

TypeScript Korea User Group Organizer

Marktube (Youtube)

Woongjae Lee

이 웅재

Overview

  • Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.

  • It uses the new standardized format for code modules included in the ES6 revision of JavaScript, instead of previous idiosyncratic solutions such as CommonJS and AMD.

  • ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries.

  • This will eventually be possible natively everywhere, but Rollup lets you do it today.

mkdir my-first-rollup-project

cd my-first-rollup-project

npm init -y

npm i rollup -D

code .
// src/main.js

import foo from './foo.js';

export default function () {
  console.log(foo);
}
// src/foo.js

export default 'hello world!';
npx rollup src/main.js -f cjs
npx rollup src/main.js -o bundle.js -f cjs
// index.js

var myBundle = require('./bundle.js');

myBundle();
node index.js

'hello world!'

Why Rollup ?

  • JavaScript 는 모듈 기능을 언어의 핵심 기능으로 포함하지 않았다.

  • ES6 에서 별도 스크립트 간 공유가 가능해졌으나, 최신 브라우저에서만 사용 가능하다.

  • Node.js 는 별도의 모듈 시스템을 사용한다.

  • 롤업을 사용하면, 표준 ES6 모듈 시스템을 사용해서 코드를 작성하고, 이것을 CommonJS, AMD, IIFE 등으로 컴파일할 수 있다.

ES Module 문법

  • import 된 값은 다른 값으로 변경할 수 없다.

  • 물론, object 나 array 와 같은 것들은 mutate 될 수 있다.

  • 이는 마치 const 와 같이 동작한다.

const something = 'value';

export { something };
import { something } from './module.js';

something = 'new value'; // error
  • Named Imports, Named Exports

  • 모듈에서 정의하고 export 한 이름 그대로 import 할 수 있다.

  • 혹은 as 를 이용해 다른 이름으로 변경하며 import 할 수 있다.

  • 마찬가지로 as 를 이용해 다른 이름으로 변경하며 export 할 수 있다.

const something = true;

export { something };
export { something as somethingElse };
import { something } from './module.js';
import { something as somethingElse } from './module.js';
  • Default Import

  • 모듈에서 default 키워드를 이용해 하나만 export 할 수 있다.

  • 그리고 default import 를 이용해 import 할 수 있다.

const something = true;

export default something;
import something from './module.js';
  • Empty Import

  • 모듈을 로드하지만 새로운 import 개체를 만들지 않는다.

  • 이는 polyfill 에 유용하거나,
    가져온 코드의 주요 목적이 프로토타입을 처리하는 것일 때 유용합니다.

import './module.js';
  • Dynamic Import

  • 애플리케이션의 code-splitting 과
    필요할 때 모듈을 가져와 즉석에서 사용하는 데 유용하다.

import('./modules.js')
  .then(({ default: DefaultExport, NamedExport }) => {
  // do something with modules.
});
// incrementer.js

export let count = 0;

export function increment() {
  count += 1;
}
// main.js

import { count, increment } from './incrementer.js'; // live bindings

console.log(count); // 0
increment();
console.log(count); // 1

count += 1; // Error — only incrementer.js can change this

How bindings work

rollup.js 를 이용한 자바스크립트 번들러 이해하기

By Woongjae Lee

rollup.js 를 이용한 자바스크립트 번들러 이해하기

  • 482