search
HomeWeb Front-endJS TutorialHow to run esm code directly in Nodejs or browser

How to run esm code directly in Nodejs or browser? The following article will introduce to you how to run ESM code in Nodejs or browser. I hope it will be helpful to you!

How to run esm code directly in Nodejs or browser

Commonjs

  • CommonJs can dynamically load statements, and the code occurs at runtime
  • CommonJs exported values ​​​​are copies , difficult to troubleshoot causing variable pollution

ES module (hereinafter referred to as esm)

#esm is the future of JavaScript modularity. Because it solves the problems of variable pollution, code maintenance, and code dependency. It makes your code more scientific. This is why deno uses esm by default.

Back to the topic, is there any way for us to run esm code directly in Nodejs or the browser? This is an interesting and practical question. [Recommended learning: "nodejs Tutorial"]

How to allow

1. Use the compilation tool to run esm

The most common way is to use packaging tools such as webpack with babel. With the popularity of webpack and vue, these tools seem to have become standard, but the shortcomings of webpack are also obvious. It allows commonjs and esm to be mixed, resulting in some irregularities in code writing. I believe this is the case. It commonly appears in business code and also exists in well-known third-party component libraries such as antd3.

And rollup is compiled based on ES6 syntax specifications. It is lightweight and compact, and is very suitable for packaging npm libraries. Emerging packaging tools such as esbuild and swc can also implement compilation and packaging. Even though the speed is getting faster and faster, the compilation process is still required. A very important feature of these repositories is the use of esm syntax.

The above tools can be applied to esm syntax compilation, but there are many projects that do not necessarily require the time-consuming process of packaging and compilation, such as some cli tools, simple microservices, etc. How to ensure efficient and correct running of esm What about the code?

2. Use third-party libraries to run esm

When the Nodejs version is lower, we can use some tools. There are several ways to use the tools. One It is Module Loader, and the other is Command Line (cli for short).

Module Loader, here we introduce standard-things/esm, which can preload esm packages provided by third parties. From now on, it can be babelless and bundleless. You can run esm code directly without using large compilation tools. The usage is as follows.

node -r esm index.js

Similarly, egoist/esbuild-registerWith the support of esbuild, this library can also achieve the effect of Module Loader. Taking advantage of the high-performance features of esbuild, the code runs more efficiently.

node -r esbuild-register index.js

Command Line, based on the encapsulated cli, is just a different form of pre-processing of modules. babel-node Directly take advantage of its babel syntax to run esm code. Since babel itself is still an implementation of js, its official documentation also states that it is not recommended to be used in a production environment, as it will cause high memory usage, which is also a common problem with this type of tool.

babel-node index.js

Similarly, esnoYou can run esm code directly on the command line. The principle is based on esbuild. This method is more recommended here. Since esbuild is implemented in the go language, it can solve the problem of high memory usage to a large extent and ensure a certain execution performance.

esno index.ts
esmo index.ts

This type of third-party warehouse is suitable for use in low-version nodejs and non-production environments. They exist for convenience, not practicality and stability. How to run esm code efficiently?

3.Native Nodejs runs esm

Node verison 13.2.0 starts to officially support the ES Modules feature

所以利用 Native Nodejs 环境运行 esm 代码是非常必要的,高版本的 Nodejs 提供了直接运行 esm 的功能,这里建议使用 lts14 版本。有两种方式运行 esm 代码:

第一种,package.json 中填写 type: "modules",表明模块的类型。此后,直接运行node index.js即可。

// pakage.json
{
  ...
  "type": "modules"
}

第二种,则是将文件名改成.mjs,标明该文件是 esm 代码。这两种方式最大的区别则是模块作用域。前者是包的作用域,它的声明是以 package 为维度。后者则是以文件为维度,不受限于包的作用域。

如何在浏览器运行 esm

How to run esm code directly in Nodejs or browser

浏览器的情况有别于 Nodejs 环境,在大部分的新版本浏览器都支持 esm 的运行。esm 级别的代码编译和打包,可以有效地减少包的体积和资源传输速度。这也是为什么像 vite 这样的框架会采用现代浏览器的打包模式(外加 legacy 兼容模式)的原因。具体的原理是在 html 当中的 script 标签加入type="module" 则表明它引入的是 esm 代码,当旧浏览器没法支持 esm 的情况下,它会读取nomodule script中的地址,读取兼容版本的 js 代码。这样一来,可以有效地减少大部分浏览器加载的 js 体积,又保证了老浏览器的兼容性问题。

<script type="module" src="dist/index.js"></script>
<script nomodule src="dist/index.legacy.js"></script>

总结

如今 Nodejs 和浏览器环境都能对 esm 语法有了很好的 Native 支持。作为前端工程师的我们,应该要保持着技术的前瞻性,在写一个仓库的时候,我们要想到要用 typescript,esm 还是 common.js 呢?为什么我们不选择比较新的 js 运行环境,迎接 Javascript 的第三个时代,参考《ESM Import 与 Bundleless》

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How to run esm code directly in Nodejs or browser. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!