Is it possible to require npm modules in a chrome

2020-03-01 05:43发布

I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please?

2条回答
放荡不羁爱自由
2楼-- · 2020-03-01 05:57

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?

查看更多
小情绪 Triste *
3楼-- · 2020-03-01 06:01

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.

查看更多
登录 后发表回答