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

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

问题描述

我试过了,但我有一个需要未定义"的错误.我找不到这方面的信息,有人可以启发我的菜鸟吗?

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?

推荐答案

这是可能的,但你必须小心.尝试 require() 一个包意味着节点将尝试在您的文件系统中定位它的文件.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 这样的模块打包器,它会生成一个 javascript 文件,其中包含通过 require() 包含的所有包的所有代码.您必须为 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.

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

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