【问题标题】:How to import jQuery into $ in a Vue.js 3 / Vite application如何在 Vue.js 3 / Vite 应用程序中将 jQuery 导入 $
【发布时间】:2020-11-22 01:42:57
【问题描述】:

我正在尝试使用 Vite (https://github.com/vitejs/vite) 在 Vue.js 3 项目中包含 jQuery。

我在 package.json 依赖项中包含 jQuery:

  "dependencies": {
    "@types/jquery": "^3.5.0",
    "jquery": "^3.5.1",
    "vue": "^3.0.0-rc.1"
  },

我在Vite的骨架main.js中导入,第一行:

import * as $ from "jquery";

但这实际上并没有将 jQuery 对象导入$(它导入了其他东西)。

但是,如果我将其更改为:

import * as jqueryExports from "jquery";
...
window.$ = jqueryExports.default;

然后一切正常。

我很确定这不是预期的方式。另外,我怀疑这个问题不是 Vite 特有的,但我没有用 Webpack 尝试过。

导入jQuery的正确方法是什么?

【问题讨论】:

    标签: jquery vue.js webpack vuejs3


    【解决方案1】:

    你试过这样吗:

    import $ from "jquery";
    

    或者尝试简单地在 vuejs 之前的 header 中加载它

    <script  src="https://code.jquery.com/jquery-3.5.1.min.js"  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="  crossorigin="anonymous"></script>
    

    【讨论】:

    • 这在main.js 文件中有效,但我无法在具有导出类的TS 模块文件中使用它(即使用export class ...)。我收到一个 TS 错误:TS1259: Module '....../node_modules/@types/jquery/index" can only be default-imported using the 'esModuleInterop' flag。但我想这是进步……
    • 有什么理由不简单地在标题中加载 jquery 吗?
    • 在 tsconfig 中尝试将 'esModuleInterop' 设置为 true。
    • 没有人想在标头脚本标签中加载 jquery,因为每个人都希望只有一个引导文件,所有导入都已完成。没有人希望在应用程序文件周围有脚本标签。
    猜你喜欢
    • 2020-12-05
    • 2021-12-03
    • 1970-01-01
    • 2021-12-01
    • 2021-05-12
    • 2019-04-24
    • 2019-02-06
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多