P粉0069779562023-08-23 20:17:35
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:
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粉8034443312023-08-23 15:44:30
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.