Home  >  Q&A  >  body text

Can be rewritten as: Is it possible to use npm modules in Chrome extensions?

<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粉217629009P粉217629009424 days ago386

reply all(2)I'll reply

  • P粉006977956

    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:

    • 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.

    reply
    0
  • P粉803444331

    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.

    reply
    0
  • Cancelreply