I am looking at a NodeJS project, which is downloaded from GitHub. It has a main file, server.js
, which uses the ES6 module import syntax like this:
import express from 'express';
import bodyParser from 'body-parser';
import fs from 'fs';
import { search } from './lib/words';
I have NodeJS version 4.6.0 installed, which is pretty old, and I do not think it supports this syntax. Instead, it should be like:
var express = require(express)
var bodyParser = require('body-parser')
...
However I can run this project correctly without error, which I think shows that NodeJS supports this syntax, but the NodeJS documentation never specifies such module syntax. What is the reason we can use it here? Thank you for help.
When you run npm start
, the start script in the package.json
is run, meaning that start.js
gets executed.
start.js
uses babel-register
to transpile the new ES6 syntax (including the imports) to plain ES5 JavaScript that Node understands on the fly. The .babelrc
shows that the es2015
preset is being used, which converts ES2015 (ES6) code to normal ES5 JS.
The particular transformer that matters to you is transform-es2015-modules-commonjs
, which will transform import
to require
as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With