javascriptnode.jsecmascript-6mjs

NodeJS require module namespaces


I thought about having my, on npmjs released, module split into 2 or more parts (versioned), but both easily requirable / importable.

The result should be:

//index1.js
const themodule = require('mymodule');

//index2.js
const themodule = require('mymodule/v2');

//index.mjs
import themodule from 'mymodule/v2';

Kind of this style.

I tried creating a subfolder named v2 in the path where the package.json:main property field points to. Did not work.

I can't seem to figure out how to be able to use the '/' in the module name / get it into there.

A helpful hint / push into the right direction would be great.

edit: folder structure:

package.json  main->lib/mod.js
lib/mod.js
lib/v2/mod.js

Solution

  • so the solution seems to be exactly as @Bergur pointed out:

    package.json:main     -> lib/index.js
    lib/index.js          (version 1)
    v2/package.json:main  -> ./index.js  (just needs a handful basic fields)
    v2/index.js           (version 2)
    

    this enables above handling with require. not sure about import.