Modules module

Import Assertions

#static import

import json from "./package.json" assert {type: "json"}
//Import all objects in the json file

#Dynamic Import

const json =
     await import("./package.json", { assert: { type: "json" } })

import.meta

ES2020 Added a meta property import.meta to the import command, which returns the meta information of the current module

new URL('data.txt', import.meta.url)

In the Node.js environment, import.meta.url always returns a local path, that is, a string of the file:URL protocol, such as file:/// home/user/foo.js

import() allows module paths to be dynamically generated

const main = document.querySelector('main')
import(`./modules/${someVariable}.js`)
  .then(module => {
    module.loadPageInto(main);
  })
  .catch(err => {
    main.textContent = err.message;
  });

Dynamically load modules

button.addEventListener('click', event => {
  import('./dialogBox.js')
    .then(dialogBox => {
      dialogBox. open();
    })
    .catch(error => {
      /\*Error handling \*/
    })
});

ES2020 Proposal introduce import() function

as keyword renaming

import {
  lastName as surname // import rename
} from './profile.js';
function v1() { ... }
function v2() { ... }
export { v1 as default };
//Equivalent to export default v1;
export {
  v1 as streamV1, // export rename
  v2 as streamV2, // export rename
  v2 as streamLatestVersion // export rename
};

Exports export

export default function () { ··· }
//aka: module.exports.default = ···

export function mymethod () { ··· }
//aka: module.exports.mymethod = ···

export const pi = 3.14159
//aka: module.exports.pi = ···

const firstName = 'Michael';
const lastName = 'Jackson';
const year = 1958;
export { firstName, lastName, year };

export *from "lib/math";

export is the new module.exports. See: Module exports

Imports import

import 'helpers'
//aka: require('···')

import Express from 'express'
//aka: const Express = require('···').default || require('···')

import { indent } from 'helpers'
//aka: const indent = require('···').indent

import *as Helpers from 'helpers'
//aka: const Helpers = require('···')

import { indentSpaces as indent } from 'helpers'
//aka: const indent = require('···').indentSpaces

import is the new require(). See: Module imports

Comments