Not able to use CJS(commons) npm package in ESM(type=module) project

Not able to use CJS(commons) npm package in ESM(type=module) project

  

I had developed one npm package for my internal use which is written in CommonJS as it uses the express.js so i kept it in common.js

but when i try to import that package in my react.js project along with the VITE it throws the bellow error.

ReferenceError: module is not defined

What i found over the internet that CommonJS packages can work on module.js without any extra configuration but then why i am getting this error.

Note:- I am using npm link to use the package locally but if I install the same package from my private npm repo then it works fine without any error and the source code on both local and live are the same.

Below is the npm package code for how i am exporting the module from the index file.

'use strict'

module.exports = require('./source');

and this is how i am importing it

import {RoutingService} from 'service-provider';

But as discussed above I am getting errors while doing this.

I also heard about the Dual Module Strategy but i don't think it's helpful here if i have a package already in the CommonJS.

Below is my package json.

"name": "service-provider",
  "version": "0.0.7",
  "description": "servi e-provider",
  "main": "index.js",
  "type": "commonjs",
  "exports": {
    ".": {
      "import": "./index.js",
      "require": "./index.js"
    }
  },

Answer

From the error I can see that the reference to the service-provider is not available. To refer to the package, please follow the below steps

  1. Run 'npm link' command in the service-provider directory.
  2. Run 'npm link service-provider' in your project directory.

By doing this a symlink will get created under the node_modules of the current project to the service-provider package.

© 2024 Dagalaxy. All rights reserved.