The es module can be executed in node; node has supported the native es module since version 8.5.2. This function can be turned on through the command line option. The es module, also known as the ECMAScript module, is a JavaScript code reuse mechanism. , but require() cannot be used in the es module.
The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.
es modules can be executed in node
Starting from version 8.5.0, Node.js begins to support native ES modules, and this feature can be turned on through command line options. The new features are largely due to Bradley Farias.
1. Demonstration
The code directory structure of this example is as follows:
esm-demo/ lib.mjs main.mjs
lib.mjs:
export function add(x, y) { return x + y; }
main.mjs:
import {add} from './lib.mjs'; console.log('Result: '+add(2, 3));
Run the demo:
$ node --experimental-modules main.mjs Result: 5
2. Checklist: Things to note
ES module:
·You cannot import modules dynamically. However, work on dynamic import() is in progress and support should be available soon.
·No meta variables such as __dirname and __filename. However, there is a proposal for a similar function: "import.meta". It might look like this:
console.log(import.meta.url);
·Now all module identifiers are URLs (this part is new in Node.js) :
·File - relative path with file extension: ../util/tools.mjs
·Library - no file extension and no path lodash
· How to better make npm libraries available in browsers (without using bundler) remains to be seen. One possibility is to introduce RequireJS-style configuration data that maps paths to actual paths. Currently, it is illegal to use bare path module identifiers in browsers.
Interoperability with CJS modules
You can import CJS modules, but they always only have the default export - that is, the value of module.exports. Making CJS modules support named exports is already being worked on, but may take a while. If you can help, you can do it.
import fs1 from 'fs'; console.log(Object.keys(fs1).length); // 86 import * as fs2 from 'fs'; console.log(Object.keys(fs2)); // ['default']
· You cannot use require() in ES modules. The main reason is:
· Path resolution works slightly differently: ESM does not support NODE_PATH and require.extensions. Also, the fact that its identifier is always a URL causes some slight differences.
· ES modules are always loaded asynchronously, which ensures maximum compatibility with the web. This loading style cannot be mixed with synchronous loading of CJS modules via require().
· Disabling synchronous module loading also leaves a fallback path for Top-level await imports of ES modules (a feature currently under consideration).
Recommended learning: "nodejs video tutorial"
The above is the detailed content of Can the es module be executed in node?. For more information, please follow other related articles on the PHP Chinese website!

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

React's componentized architecture makes scalable UI development efficient through modularity, reusability and maintainability. 1) Modularity allows the UI to be broken down into components that can be independently developed and tested; 2) Component reusability saves time and maintains consistency in different projects; 3) Maintainability makes problem positioning and updating easier, but components need to be avoided overcomplexity and deep nesting.

TonavigateReact'scomplexecosystemeffectively,understandthetoolsandlibraries,recognizetheirstrengthsandweaknesses,andintegratethemtoenhancedevelopment.StartwithcoreReactconceptsanduseState,thengraduallyintroducemorecomplexsolutionslikeReduxorMobXasnee

Reactuseskeystoefficientlyidentifylistitemsbyprovidingastableidentitytoeachelement.1)KeysallowReacttotrackchangesinlistswithoutre-renderingtheentirelist.2)Chooseuniqueandstablekeys,avoidingarrayindices.3)Correctkeyusagesignificantlyimprovesperformanc

KeysinReactarecrucialforoptimizingtherenderingprocessandmanagingdynamiclistseffectively.Tospotandfixkey-relatedissues:1)Adduniquekeystolistitemstoavoidwarningsandperformanceissues,2)Useuniqueidentifiersfromdatainsteadofindicesforstablekeys,3)Ensureke

React's one-way data binding ensures that data flows from the parent component to the child component. 1) The data flows to a single, and the changes in the state of the parent component can be passed to the child component, but the child component cannot directly affect the state of the parent component. 2) This method improves the predictability of data flows and simplifies debugging and testing. 3) By using controlled components and context, user interaction and inter-component communication can be handled while maintaining a one-way data stream.

KeysinReactarecrucialforefficientDOMupdatesandreconciliation.1)Choosestable,unique,andmeaningfulkeys,likeitemIDs.2)Fornestedlists,useuniquekeysateachlevel.3)Avoidusingarrayindicesorgeneratingkeysdynamicallytopreventperformanceissues.

useState()iscrucialforoptimizingReactappperformanceduetoitsimpactonre-rendersandupdates.Tooptimize:1)UseuseCallbacktomemoizefunctionsandpreventunnecessaryre-renders.2)EmployuseMemoforcachingexpensivecomputations.3)Breakstateintosmallervariablesformor


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
