Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 30, 2021 06:23 pm GMT

How to use MJS files in Node.js?

Today I want to show you how to import functions from *.mjs files. You can think of MJS as JavaScript code that is exported in a standardized module format. It's basically (M)odular (J)ava(S)cript. The standardization itself is called ECMAScript Modules (ESM).

By default, the Node.js platform doesn't use ES modules but CommonJS, which is a different module formatting system. Fortunately, the Node.js team introduced the concept of ES modules back in 2017 with Node v8.9.0. At that time, you could run Node.js with an additional flag (--experimental-modules) to make use of it.

Since Node v13.2.0 the experimental flag is no longer required. It only takes a few steps now to use an ECMAScript module. Let me show you how to do it.

1. Create a ES Module / MJS File

Setting up an ES module is simple: Just create a file with the *.mjs extension and export your code using the export keyword:

myFunction.mjs

export function myFunction(a, b) {  return `${a} ${b}`;}

2. Import your code

You can import an ES module with the import keyword. If you work with TypeScript, you are probably already familiar with this syntax. You can import MJS files into ordinary JavaScript (JS) files:

start.js

import { myFunction } from "./myFunction.mjs";const text = myFunction("Hello", "World");console.log(text);

Tip: Don't forget to add the *.mjs extension to you import statement. If you omit the file extension, Node.js will look for a .js file and report the following error:

node:internal/process/esm_loader: internalBinding('errors').triggerUncaughtException
Error [ERR_MODULE_NOT_FOUND]: Cannot find module

3. Set your package type to "module"

That's probably the biggest change: You have to create a property with the name type in your package.json file. To use ES modules, it has to bet set to module.

package.json

{  "name": "my-package",  "scripts": {    "start": "node src/start.js"  },  "type": "module",  "version": "0.0.0"}

If you forgot to set the type property, or if you set it to commonjs, you will run into the following error:

(node:2346) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module

Closing

Now you know the basics of using MJS files. I tested my code listings with Node v15.14.0. I wish you good luck when trying it yourself!


Original Link: https://dev.to/bennycode/how-to-use-mjs-files-in-node-js-23ep

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To