DEV Community

Ruxin Qu
Ruxin Qu

Posted on • Updated on

JavaScript: Module export and import (browser and Node.js runtime)

====================================

Browser runtime

  1. Open a HTML file with js modules directly from default browser will throw an error. You need to create a local server with VSCode.
  2. The script.js file has imported module should have an attribute type= 'module' when linking to HTML, the file has exported module doesn't need to be linked to HTML.
  3. To export several functions, export {func1, func2...} or add export before declare the function
  4. To import a function func and rename it to newfunc, import {func as newfunc} from 'path'
  5. To export a function as default, use export {func as default} or simply export default func
  6. To import a default value, import importfunc from path works the same with import { default as importedResources } from 'path'
  7. object-destructuring in import. MDN Web Docs on object destructuring
const resources = {
  func1,
  func2
}
export default resources;

import resources from 'path'
const {func1, func2} = resources
Enter fullscreen mode Exit fullscreen mode

====================================

Node.js runtime

  1. module.exports.func1 = func1 to export function1.
  2. const func1 = require('./path') to import values. For built in module, no need to provide the path.
  3. object-destructuring in import:
module.exports = {
  func1,
  func2
}

import way 1:
const func = require('path');
const func1Value = func.func1;
const func2Value = func.func2;

import way 2:
const {func1, func2} = require('path')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)