Matt
Matt

Reputation: 8942

How to use ES6 imports and CommonJS imports in the same file in Node.js

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

Answers (1)

x00
x00

Reputation: 13833

Docs:

  1. Differences between ES modules and CommonJS
  2. module.createRequire(filename)
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

Related Questions