要求未在 Chrome 扩展中定义

The require is not defined in Chrome Extension

我有一个 Chrome 扩展,我想测试 a.js

在chrome中,a.js依赖于b.js——加载前注入a.js

我正在使用 mocha 在 Node.JS 中编写一些单元测试。它要求我在 a.js 的开头放置 import 或类似 const { functions } = require('b.js') 的内容。但是在chrome中,require没有定义。

我将下面的内容放在 a.js 的开头,但是 Chrome 扩展名不起作用(我看不到错误)

if (typeof module !== 'undefined'  && typeof module.exports !== 'undefined') {
   const { functions } = require('b.js'); 
}

如何让它在 Chrome 和单元测试中工作?现在,我可以在 npm 运行 test 之前手动添加 require 并在打包 Chrome 扩展时将其删除.

我终于用webpack解决了这个问题。

  1. 运行 使用 npm run test
  2. 进行单元测试
  3. 使用 npm run build 调用 webpack -p 将 ES6 类 打包成 Chrome 扩展可以理解的内容。

你可以看到这个项目,它运行得很好:https://github.com/DoctorLai/VideoDownloadHelper