2

我正在使用 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,这在某种程度上并不满足。

4

2 回答 2

3

Parcel 实际上并没有参与这个问题,主要是 jQuery/Bootstrap 依赖于在全局范围内公开的$and函数。jQuery

通过执行以下操作很容易存档(仅适用于 JS,因为 TS 会抱怨 window 没有属性$and jQuery):

import jquery from "jquery";
window.$ = window.jQuery = jquery;
import "bootstrap";

但是由于您使用的是 TypeScript,因此您需要做更多工作才能使 linting 和智能感知支持也正常工作。

  1. 安装 TypeScript 定义文件npm install --save-dev @types/jquery @types/bootstrap
  2. 用于import * as $ from 'jquery';导入它。
  3. 为 DOM api 配置库,因为默认情况下 TypeScript 未启用它们,这将允许您使用正确的windowdocument但您需要更改window(<any> window)

    tsconfig.json

    {
      "compilerOptions": {
        //...
        "lib": ["dom"],
        //...
      },
    }  
    
于 2018-10-25T19:41:17.137 回答
1

我用这个 .babelrc添加了一个 babel 插件( babel-plugin-auto-import )

  {
    "plugins": [[
      "auto-import", {
        "declarations": [
          { "anonymous": ["jQuery"], "path": "jquery" }
        ]
      }
    ]]
  }

一切似乎都在工作。

新的 package.json

{
  "name": "pc",
  "version": "0.1.0",
  "description": "",
  "author": "",
  "license": "",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-plugin-auto-import": "^0.9.3",
    "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"
  }
}
于 2018-10-25T18:23:29.087 回答