Skip to main content

Command Palette

Search for a command to run...

3 ways to add npm package in Chrome extension.

Updated
2 min read

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

You may think then how does node.js find packages' path ??

When you run npm command. NPM replace package name with real path. You need to just find 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"
   },
   }

This is 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);

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 3: 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();
  • Auto-fix virtual path to real path of all dependencies
import setAllPkgPath from "path-fixxer";
setAllPkgPath();
  • Auto-fix virtual path to real path of one dependency
import { realPath } from "path-fixxer";
setPkgPath("package_name");

To contribute or create new issues, visit Github pages path-fixxer. Thanks for reading