This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge
A module is a JavaScript file that exports one or more values. The exported value can be a variable, object, or function.
Node.js applications are made up of modules, and the module system uses the CommonJS specification, which is not a formal part of the JavaScript language specification.
In CommonJS, there is a global method called require(), which is used to load modules.
// Load the path module
const path = require('path')
Copy the code
The ECMAScript module (ES module or ESM) is an added module to the JavaScript language specification that seeks to unify and standardize how modules are loaded in JavaScript applications.
The following import syntax consists of the following ES module standards for importing modules exported from different JavaScript files:
import XXX from 'xxx'
Copy the code
Node.js does not support importing ES6 directly. Try writing import syntax in a JS file:
// index.js
import { sep } from 'path'
console.log('print: ', sep)
Copy the code
When you run node.js with NPM start or NPM run dev, you will encounter the following error:
The program crashed because we imported the PATH module using the ES module syntax.
For now, the quickest solution is to set “type”: “module” in the package.json file, as recommended by Node.js.
{
"type": "module"
}
Copy the code
This solution works with the latest Node.js version 14.x.x and above (15.6.0 at the time of this writing).
The environment version is earlier than Node V. 14
Another way to solve this problem is to use Babel. It is a JavaScript compiler that allows you to write JS using the latest syntax. It can be used in any project written in JavaScript, so it can also be used in node.js projects
Start by installing the following developer dependencies from the terminal window:
$ npm i -D @babel/core @babel/preset-env @babel/node
Copy the code
Then create a file called babel.config.json in the root directory of your node.js project and add the following:
module.exports = {
"presets": ["@babel/preset-env"]}Copy the code
The @babel/node package is a CLI utility that compiles JS code with Babel presets and plug-ins before running the Node.js project. This means that it will read and apply any configuration mentioned in babel.config.json before executing the Node project.
Replace the node with babel-node to execute the server in the start or dev script.
Example of running a Node server using the NPM run dev script:
{
"scripts": {
"dev": "nodemon --exec babel-node server.js"}}Copy the code