An overview,

Let’s start with some code:

// index.js
import createMathOperation from './.internal/createMathOperation.js'

const add = createMathOperation((augend, addend) = > augend + addend, 0)

console.log(add(6.4));

export default add

Copy the code

When we execute Node index.js on the terminal, we get an error:

That is, we cannot run the ESM code directly.

Node Verison 13.2.0 officially supports ES Modules. There are two ways to do this:

  1. inpackage.jsonSet in the"type": "module"
  2. Change the file suffix tomjs

According to the second method, to facilitate debugging, I developed a command line tool — uuNode, which converts JS files into MJS without overwriting the original file, executes the corresponding MJS file, and returns the result.

Second, the installation

NPM use:

npm install uunode -g

Yarn using:

yarn add uunode -g

Sudo NPM install uunode -g or sudo yarn add uunode -g

Three, use examples

uunode [example.js]

As shown in the example when we runuunode [example.js]When, it produces one.uunodeThe folder in which will be storedmjs Files (default does not keep files, you can add-kParameter save file). And performnode .uunode/example.jsReturns the corresponding result.

You can also use uunode [example.js] -s to remove the console.

Parameters supported:

The parameter value meaning
-s Get rid ofconsole
-k Keep the post-production menu

Four, in the future

Deno was discovered while exploring how to write uuNode, which was also developed by NodeJS author Ryan Dahl.

Node cannot handle ESM module issues, will be resolved in Deno. For more on denO, see this article.

How to write an automation tool

NPM publish publishes a package corresponding to name in package.json.

In package.json, bin represents the corresponding instruction.

"bin": {
  "uunode": "bin/index.js"
},
Copy the code

After NPM install uunode -g is executed, you can run the corresponding command in bin.

Five or more

  1. Write a node.js command line program by hand

  2. How to develop a Node.js command-line (CLI) tool from scratch

  3. What is AMD, CommonJS, UMD, ESM?

  4. Will we be able to use ES Modules in Node in 2020