是否可以在扩展中需要npm模块? [英] Is it possible to require npm modules in a chrome extension ?

查看:105
本文介绍了是否可以在扩展中需要npm模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过了,但我有一个'require is not defined'的错误。我找不到有关这方面的信息,请问有人可以启发我的noob吗?

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?

推荐答案

这是可能的,但是您必须小心。试图要求()包意味着节点将尝试在文件系统中找到它的文件。 chrome扩展只能访问您在清单中声明的​​文件,而不是您的文件系统。

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.

为了解决这个问题,可以使用Webpack这样的模块打包器,它将生成一个包含通过require()包含的所有包的所有代码的单个JavaScript文件。您必须为您的Chrome扩展的每个组件生成一个单独的模块(例如一个用于背景页面,一个用于内容脚本,另一个用于弹出窗口),并在清单中声明每个生成的模块。

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.

为了避免试图设置你的编译系统来使require()成为可能,我建议从一个样板项目。您可以查看我的扩展程序,看看我是如何做到的。

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.

这篇关于是否可以在扩展中需要npm模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆