Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does NodeJS support "Import" style module loading? [duplicate]

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.

like image 991
IcyBrk Avatar asked Mar 11 '23 12:03

IcyBrk


1 Answers

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.

like image 131
Aurora0001 Avatar answered May 05 '23 08:05

Aurora0001