Using ES6 Modules in Node.js
To get this working install Node.js 12:
nvm install 12
Then ensure your files end in .mjs to specify them as modules. Then either run Node.js with --experimental-modules or install the 'esm' package and use -r esm instead. This installation also gets rid of the warning messages that --experimental-modules gives. Here is an example:
backendImports.mjs
import moduleA from './testModule'; moduleA.helloWorld(); // Hello world console.log(moduleA.property1); // value1
testModule.mjs
export const helloWorld = () => { console.log('Hello world'); }; export const property1 = 'value1'; export default { helloWorld, property1 };
Which is run with node -r esm 2019/backendImports.mjs if you installed 'esm'. So far that does exactly what require does, but now at least it matches more modern import syntax used by bundlers like Webpack (which is used by React and modern Angular). Though the real advantage is the flexibility it gives. For example, specific parts of the module can be extracted instead in one line of code:
import { helloWorld } from './testModule'; helloWorld(); // Hello world
All parts of the module can be automatically imported too with * and assigned to a namespace in case no default export was given:
import * as moduleA2 from './testModule'; moduleA2.helloWorld(); // Hello world console.info(moduleA2.property1); // value1
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/backendImports.mjs
















