Basic use of ES Module

ES Module

The blogger will continue to update various front-end technologies. If you like, you can pay attention to, collect and praise the blogger's articles.

Basic characteristics of ES Module

  • ESM automatically adopts strict mode and ignores' use strict '
  • Each ES Module runs in a separate private scope
  • ESM requests external JS modules through CORS
  • The script tag of ESM will delay the execution of the script (after the browser page is rendered)

export

When creating a JavaScript module, the export statement is used to export real-time bound functions, objects or original values from the module so that other programs can use them through the import statement. The exported binding value can still be modified locally. When using import for import, these binding values can only be read by the import module, but if these binding values are modified in the export module, the modified values will be updated in real time.

Whether you declare it or not, the exported module is in strict mode. The export statement cannot be used in embedded scripts.

// Export individual properties
export let name1, name2, ..., nameN; // also var, const
export let name1 = ..., name2 = ..., ..., nameN; // also var, const
export function FunctionName(){...}
export class ClassName {...}

// Export list
export { name1, name2, ..., nameN };

// Rename export
export { variable1 as name1, variable2 as name2, ..., nameN };

// Deconstruct export and rename
export const { name1, name2: bar } = o;

// Default export
export default expression;
export default function (...) { ... } // also class, function*
export default function name1(...) { ... } // also class, function*
export { name1 as default, ... };

// Merge modules
export * from ...; // does not set the default export
export * as name1 from ...;
export { name1, name2, ..., nameN } from ...;
export { import1 as name1, import2 as name2, ..., nameN } from ...;
export { default } from ...;

import

A static import statement is used to import a binding exported by another module. Whether strict mode is declared or not, the imported module runs in strict mode. In the browser, the import statement can only be used in the label of script declaring type="module".

In addition, there is a function like dynamic import(), which does not need to rely on the script tag of type="module".

Using the nomodule attribute in the script tag ensures backward compatibility.

Dynamic import() is very useful when you want to load modules according to certain conditions or on demand. Static import is the best choice for initializing loading dependencies. Using static import is easier to benefit from code static analysis tools and tree shaking.

// Import the contents of the whole module
import * as myModule from '/modules/my-module.js';

// Import a single interface
import {myExport} from '/modules/my-module.js';
// Import multiple interfaces

import {foo, bar} from '/modules/my-module.js';

// Import interface with alias
import {reallyReallyLongModuleExportName as shortName} from '/modules/my-module.js';

// Renaming multiple interfaces during import
import {
  reallyReallyLongModuleMemberName as shortName,
  anotherLongModuleName as short
} from '/modules/my-module.js';

// Importing a module for side effects only
// The whole module is imported only for side effects (neutral words, no derogatory meaning), and no content (Interface) in the module is imported. This will run the global code in the module, but will not actually import any values.
import '/modules/my-module.js';

// Import defaults
import myDefault from '/modules/my-module.js';
import myDefault, * as myModule from '/modules/my-module.js';
// myModule used as a namespace
import myDefault, {foo, bar} from '/modules/my-module.js';
// specific, named imports

// Dynamic import
import('/modules/my-module.js')
  .then((module) => {
    // Do something with the module.
  });
let module = await import('/modules/my-module.js');

node environment

es module usage

index.mjs

// First, change the file extension from js changed to mjs;
// Second, additional ` -- experimental modules' parameters need to be added during startup;

import { foo, bar } from './module.mjs';

console.log(foo, bar);

// At this point, we can also load the built-in module through esm
import fs from 'fs';
fs.writeFileSync('./foo.txt', 'es module working');

// You can also directly extract the members in the module. The built-in module is compatible with the method of extracting members in ESM
import { writeFileSync } from 'fs';
writeFileSync('./bar.txt', 'es module working');

// NPM modules of third parties can also be loaded through esm
import _ from 'lodash';
_.camelCase('ES Module');

// Not supported because all third-party modules are exported as default members
// import { camelCase } from 'lodash'
// console.log(camelCase('ES Module'))

Interact with CommonJS

  • CommonJS module can be imported into ES Module
  • ES Module cannot be imported into CommonJS
  • CommonJS always exports only one default member
  • Note that import is not a deconstruction of the exported object

commonjs.js

// The CommonJS module always exports only one default member

// module.exports = {
//   foo: 'commonjs exports value'
// }

// exports.foo = 'commonjs exports value'

// ES Module cannot be loaded through require in CommonJS module

// const mod = require('./es-module.mjs')
// console.log(mod)

es-module.mjs

// CommonJS module can be imported into ES Module

// import mod from './commonjs.js'
// console.log(mod)

// Members cannot be extracted directly. Note that import is not an export object

// import { foo } from './commonjs.js'
// console.log(foo)

// export const foo = 'es module export value'

Differences with CommonJS

esm.mjs

// There is no module global member in ESM

// //Load module function
// console.log(require)

// //Module object
// console.log(module)

// //Export object alias
// console.log(exports)

// //Absolute path of the current file
// console.log(__filename)

// //Directory of current file
// console.log(__dirname)

// -------------

// Require, module and exports are naturally replaced by import and export

// __ filename and__ dirname is obtained through the meta attribute of the import object
// const currentUrl = import.meta.url
// console.log(currentUrl)

// Convert to a path through the fileURLToPath method of the url module
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(__filename);
console.log(__dirname);

For versions after Node v12, you can use package Add the type field as module in JSON and change the default module system to ES Module. At this time, there is no need to change the file extension to mjs

If you need to continue using CommonJS with type=module, you need to modify the file extension to cjs

For earlier nodes JS version, you can use Babel to achieve ES Module compatibility

// Configuration: the first method
{
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ]
}
// Configuration: the second method (Collection)
{
"presets":["@babel/preset-env"]
}

Syntax of specific Module


Author: Wuner
Link: https://www.jianshu.com/p/36ec85a2b394
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Keywords: Javascript Front-end ElasticSearch

Added by nitroxman on Tue, 15 Feb 2022 05:25:41 +0200