Is it possible to require npm modules in a chrome extension ?

Solution 1:

It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem.

To get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest.

To avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it.

Solution 2:

It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js?

Solution 3:

An updated answer for 2022

Short answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate "scaffolding" for a Chrome extension:

  • Extension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code).
  • Chrome Extension CLI

Benefits of using them:

  • New projects are initiated with a default project file structure. Super helpful.
  • They support modern Javascript (ES6, ES2021), so modules work fine.
  • They already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own.
  • You can use npm as normal to install any packages/dependencies you need.

Then of course, let the official documentation for Chrome Extensions guide you through the rest.