JavaScript Modules

Modules memisahkan kode ke file-file terpisah.

Export

  • export const x = ... — named export
  • export default ... — default export (satu per file)

Import

  • import { x } from './file.js' — named
  • import x from './file.js' — default
  • import * as mod from './file.js' — semua

Gunakan <script type="module"> di HTML.

script.js
Try It →
// In real projects, these would be separate files:

// === math.js ===
// export const add = (a,b) => a+b;
// export const multiply = (a,b) => a*b;
// export default class Calculator { ... }

// === app.js ===
// import Calculator, { add, multiply } from './math.js';
// import * as math from './math.js';

const o = document.getElementById('output');
o.innerHTML = 
  '// math.js
'+
  'export const add = (a,b) => a+b;
'+
  'export const multiply = (a,b) => a*b;
'+
  'export default class Calculator { }

'+
  '// app.js
'+
  'import Calculator from \'./math.js\';
'+
  'import { add, multiply } from \'./math.js\';
'+
  'import * as math from \'./math.js\';

'+
  '// HTML
'+
  '<script type="module" src="app.js"><\/script>';