我正在使用 parcel 来处理 webextension 的打字稿。JQuery 及其类型定义通过 npm 安装。在我的打字稿文件的顶部,我有:
import $ from "jquery";
import "bootstrap";
但是在运行时,Chrome 会抱怨 jquery 没有定义。重现问题的最小示例在 git 上:https ://github.com/lhk/parcel_jquery_bug_demo
git clone https://github.com/lhk/parcel_jquery_bug_demo
cd parcel_jquery_bug_demo
npm install
parcel build src/manifest.json
现在您可以打开 chrome 并加载 dist 文件夹
git repo 包含:
src/manifest.json
{
"manifest_version": 2,
"name": "pc",
"version": "0.0.1",
"description": "none",
"author": "",
"content_security_policy":"script-src 'self'; object-src 'self'",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"./content/index.ts"]
}
]
}
src/content/index.ts
import $ from "jquery";
import "bootstrap";
$(function () {
$('[data-toggle="popover"]').popover();
});
./package.json
{
"name": "pc",
"version": "0.1.0",
"description": "",
"author": "",
"license": "",
"devDependencies": {
"parcel-plugin-web-extension": "^1.4.0",
"typescript": "^3.1.3"
},
"dependencies": {
"@types/bootstrap": "^3.3.7",
"@types/jquery": "^3.3.10",
"bootstrap": "^3.3.7",
"jquery": "^3.3.1"
}
}
在 chrome 中加载扩展后,您可以加载任何网站。错误信息是:
未捕获的 ReferenceError:未定义 jQuery
我在用着:
- 包裹 1.10.1
- 节点 v8.12.0
- npm 6.4.1
- ubuntu 18.04.1 64位
- 铬 70
我认为这个问题与bootstrap的导入有关。以下代码有效:
import $ from "jquery";
//import "bootstrap";
$(function () {
//$('[data-toggle="popover"]').popover();
$('[data-toggle="popover"]').click(function(){});
});
所以我的打字稿代码的依赖实际上是由包裹处理的。但是 bootstrap 也需要 jQuery,这在某种程度上并不满足。