Reputation: 8942
I came across tutorials on how to use ES6 imports in Node.js using Babel, but then CommonJS imports don't work. I would like to use ES6 imports and CommonJS imports in the same files in Node.js (Express.js).
main.js
const jsdom = require("jsdom");
import {GotRequestFunction} from 'got';
Is this possible?
Upvotes: 7
Views: 2598
Reputation: 13833
Docs:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
import { A } from "./A.mjs" // NB: .mjs extention
console.log(A) // it works
const fs = require('fs')
console.log(fs) // it works as well
If you don't like .mjs
extension, then follow this advice given by the the node executable itself.
`Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.`
Upvotes: 8