require-from-esm

0.0.3 • Public • Published

require-from-esm

⚠️ Warning note ⚠ ️

  1. This is very experimental
  2. Node.js' latest version (12.0.0) is required
  3. You should run Node.js with the --experimental-modules flag
  4. You probably should run Node.js with the --es-module-specifier-resolution=node flag

require-from-esm is a small package with literally few lines aiming to provide interoperability between CJS modules and ES modules.
To be more specific, require-from-esm let you require CJS modules with the old friend Node.js global require() from ES modules.
With ES modules on Node.js we can use almost every feature from ECMA modules (still experimental).

Example:

import require from 'require-from-esm';
import path from 'path';
const mymodule = require('../../mymodule.cjs'); // You should use `../../` for local modules *

console.log(path.normalize('/foo/bar//baz/asdf/quux/..'));
console.log(mymodule);

For local modules you should use require(../../MYMODULE) instead of require(./MYMODULE).
We don't have __dirname and __pathname globals when using ES modules.
No solution was found to fix it until now. PRs are welcome.

How to use

  1. Be sure you're using Node.js >12.0.0
  2. The flags, you should use the flags: --experimental-modules and --es-module-specifier-resolution=node
  3. You can use npm scripts to run your app, something like this:
  "scripts": {
    "start": "node --experimental-modules --es-module-specifier-resolution=node index.js"
  },
  1. Make sure you have the "type": "module" on your package.json

Further reading:
https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff
http://2ality.com/2019/04/nodejs-esm-impl.html
https://scotch.io/tutorials/new-ecmascript-modules-in-node-v12#toc-new-features-in-node-v12

/require-from-esm/

    Package Sidebar

    Install

    npm i require-from-esm

    Weekly Downloads

    2

    Version

    0.0.3

    License

    MIT

    Unpacked Size

    3.02 kB

    Total Files

    5

    Last publish

    Collaborators

    • jaydson