javascript - 使用 parcel 引入 typescript 依赖项
问题描述
我正在使用 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,这在某种程度上并不满足。
解决方案
Parcel 实际上并没有参与这个问题,主要是 jQuery/Bootstrap 依赖于在全局范围内公开的$
and函数。jQuery
通过执行以下操作很容易存档(仅适用于 JS,因为 TS 会抱怨 window 没有属性$
and jQuery
):
import jquery from "jquery";
window.$ = window.jQuery = jquery;
import "bootstrap";
但是由于您使用的是 TypeScript,因此您需要做更多工作才能使 linting 和智能感知支持也正常工作。
- 安装 TypeScript 定义文件
npm install --save-dev @types/jquery @types/bootstrap
- 用于
import * as $ from 'jquery';
导入它。 为 DOM api 配置库,因为默认情况下 TypeScript 未启用它们,这将允许您使用正确的
window
,document
但您需要更改window
为(<any> window)
tsconfig.json
{ "compilerOptions": { //... "lib": ["dom"], //... }, }
推荐阅读
- android - SeekBar 删除一个选择
- excel - VBA宏卡在循环中
- c - 在 Windows 10 Pro 上使用 CodeBlocks 在 C 中计算伯努利 nTh 数的最佳方法
- vba - VBA将公式应用于列,然后根据公式结果为单元格着色
- python - Python中list[-1]的含义
- progressive-web-apps - 如何在手机的渐进式 Web 应用程序中获取实时心率数据?
- sql - 选择独特的组合(两边都独特)
- javascript - 单击调用javascript函数以隐藏输入的按钮时提交表单
- mysql - 仅当 `in` 子句中的值存在时才返回值
- sql-server - 为什么 Sql Server SELECT 不返回所有条目?