-1

I'm updating a Node.js project to support both CommonJS and ES Modules (Dual Package). My current issue appears when trying to load the module from the project root using exports field instead of main.

Project Structure

MiProject/
├── src/
│   ├── index.js  //CommonJS (module.exports)
│   └── index.mjs // ES Module (export default)
├── test/
│   ├── require.test.js  ← uses require('../')
│   └── import.test.js   ← uses import from '../'
└── package.json

Current Behavior

Inside test/require.test.js:

const mymodule = require('../'); 

This works only when package.json uses:

{
  "main": "./src/index.js"
}

But if I replace main with:

{
  "exports": "./src/index.js"
}

Node.js fails to load the module using require('../').

I need to implement conditional exports so the package can be imported using:

import mymodule from 'MiProject'; // ESM
const mymodule = require('MiProject'); // CommonJS

Meaning I must use exports instead of main, with support for both syntaxes.

1

1 Answer 1

-2
{
  "name": "MiProject",
  "version": "1.0.0",
  "type": "commonjs",        // optional; keep default CommonJS interpretation
  "main": "./src/index.js",  // optional compatibility fallback for older tools
  "exports": {
    ".": {
      "import": "./src/index.mjs",
      "require": "./src/index.js"
    }
  }
}
New contributor
Nikunj Gupta is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.