es6 foundation 0x019: modularization

Posted by muitine on Sun, 08 Dec 2019 08:26:49 +0100

0x000 overview

Modularity is the inevitable trend of a large project.

0x001 named export

You can use the export keyword to export what you want to export. You can export constants, variables, functions, and classes,

// export.js

export var var0 = 'var0' // Export var declaration directly
export let let0 = 'let0' // Export let declaration directly
export const const0 = 'const' // Direct export const export
export function func1() {} // Direct export function
export function* funcx() {} // Export generator functions directly
export class class0{} // Direct export class

let variable = 'variable' 
export {variable} // Declaration before export, you need to use {} package

function func2(){}
export {func2} // Declaration before export, you need to use {} package

function* funcx(){}
export {funcx} // Declaration before export, you need to use {} package

class class1{}
export {class1} // Declaration before export, you need to use {} package
export {class1 as Person} // Alias export

0x002 named import

Named import requires {} parcels, which can import multiple named exports at the same time

import {var0} from './export' // Import var0
import {let0} from './export' // Import let0
import {const0} from './export' // Import const0
import {func1} from './export' // Import func1
import {funcx} from './export' // Import funcx
import {class0} from './export' // Import class0

import {var0, let0} from "./export"; // Import multiple command exports at the same time
import {Person as class1} from "./export"; // Take alias after import

0x003 default export

The default export can use the default keyword and can be exported anonymously

export default 1 // Default export constant
export default function () {} // Default export
export default () => {}
export default function* () {}
export default class {}

0x004 default export

Because the default export is anonymous, you can import it with any name without using {} package

import num from './export'
import func from './export'
import arrowFunc from './export'
import generatorFunc from './export'
import class0 from './export'

0x005 import all

Import all exports of a module into the alias

import * as MyModule from './export'

0x006 redirection

Export the contents of another module directly as the current module

export {var0} from './export'
export * from './export'

Topics: Javascript