DEV Community

anil kumar
anil kumar

Posted on

3 ways to add npm package in chrome extension.

When you try to add npm packages in chrome extension.
Chrome extension show error
Import path must start with ./ or /

You might think then how node.js find path ??
When you run npm command. NPM replaces package name with real path.
You need to just find pkg's real path so that Chrome browser will find it.
Real path like this:

/node_modules/pkg-name/dist/main.js

I show you 3 different methods, how to add npm packages in your chrome extension?

Method 1: find Manually

First, Go to node_modules directory then
go to npm package directory and open package.json.
Find exports key value and copy import file value or
file with .js or .mjs file extension.

example:

   "exports": {
   ".": {
     "require": "./lib/postcss.js",
     "import": "./lib/postcss.mjs",
     "types": "./lib/postcss.d.ts"
   },
   }
Enter fullscreen mode Exit fullscreen mode

This is a relative path. Chrome browser cannot find this path.
We need to convert this into absolute path by joining path.
/node_modules/{pkg_name}/{copied_path}

Example:
/node_modules/postcss/lib/postcss.mjs
Now use this file path in place of package_name.

Method 2: nodejs API
Create path.js file and add this line.

const fullPath = await import.meta.resolve("package_name");
const path = fullPath?.match(/(\/node_modules.*)/)[0];
console.log(path);
Enter fullscreen mode Exit fullscreen mode

Then add this line inside scripts in package.json and run npm run path.
"path": "node --experimental-import-meta-resolve path.js",
Copy console output text.
Now use this file's real path in place of package_name.

Method 2: Automatic find and replace
Install other npm package to find and replace
npm packages' virtual path to real path so that chrome browser will find it.

Install Path-fixxer

npm i path-fixxer

path-fixxer provide 3 api to find and fix path.

  • Generate path.json file with absolute path of all dependencies.
import { pkgPathJson } from "path-fixxer";
pkgPathJson();
Enter fullscreen mode Exit fullscreen mode
  • Auto-fix virtual path to real path of all dependencies
import setAllPkgPath from "path-fixxer";
setAllPkgPath();
Enter fullscreen mode Exit fullscreen mode
  • Auto-fix virtual path to real path of one dependency
import { realPath } from "path-fixxer";
setPkgPath("package_name");
Enter fullscreen mode Exit fullscreen mode

For contribute or create new issues, visit github page path-fixxer.
Thanks for reading

Top comments (0)