Can be rewritten as: Is it possible to use npm modules in Chrome extensions?
P粉217629009
P粉217629009 2023-08-22 23:09:19
0
2
440
<p>I tried it, but got a "require is not defined" error. I can't find information about this error, can someone please explain it to me? </p>
P粉217629009
P粉217629009

reply all(2)
P粉006977956

Updated Answers for 2022

Short answer: Yes, you can require/import packages. Rather than laboriously setting up and configuring a packaging tool like Webpack yourself (especially if you haven't used them), there are now build tools you can use to create boilerplate code for Chrome extensions:

Benefits of using them:

  • New projects will initialize a default project file structure, which is very helpful.
  • They support modern JavaScript (ES6, ES2021), so modules will work properly.
  • They have integrated and pre-configured packaging tools (I think it was Webpack in both cases above). Therefore, you don't need to install and configure any tools yourself.
  • You can use npm as usual to install any packages/dependencies you need.

Then, of course, let the Chrome extension's official documentation guide you through the rest.

P粉803444331

It's possible, but you have to be careful. Attempting to use require() to load a package means that Node will try to locate its files in your file system. Chrome extensions can only access files you declare in your manifest, not your file system.

To solve this problem, use a module packaging tool like Webpack, which will generate a single JavaScript file containing the code for all packages introduced via require(). You need to generate a separate module for each of your Chrome extensions (e.g. background pages, content scripts, popups) and declare each generated module in the manifest.

To avoid trying to set up the build system to make require() available, I recommend starting with a boilerplate project . You can check out My extension to see how I did it.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template