如何使用 ES6 语法导入 jquery?

新手上路,请多包涵

I’m writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for样式。

索引.js

 import * as stylesheet from '../assets/styles/app.scss';
import * as jquery2 from '../dist/scripts/jquery.min';
import * as jquery3 from '../node_modules/jquery/dist/jquery.min';

console.log($('my-app'));

索引.html

 <!DOCTYPE html>
<html lang="fr">
<head>
<body>
<script src="dist/app.js"></script>
</body>
</html>

项目结构

.
├── app/
│   ├── index.js
├── assets/
├── dist/
│   ├── scripts/
│   │   ├── jquery.min.js
├── index.html
├── node_modules/
│   ├── jquery/
│   │   ├── dist/
│   │   │   ├── jquery.min.js
├── package.json
└── tests/

包.json

   …
  "scripts": {
    "build:app": "browserify -e ./app/index.js -o ./dist/app.js",
    "copy:jquery": "cpy 'node_modules/jquery/dist/jquery.min.js' ./dist/scripts/",
    …
  },
  "devDependencies": {
    "babel-core": "6.3.x",
    "babel-preset-es2015": "6.3.x",
    "babelify": "7.2.x",
    "cpy": "3.4.x",
    "npm-run-all": "1.4.x",
    "sassify": "0.9.x",
    "semantic-ui": "2.1.x",
    …
  },
  "browserify": {
    "transform": [
      [ "babelify", { "presets": [ "es2015"]}],
      [ "sassify", { "auto-inject": true}]
    ]
  }

问题

使用经典 <script> 标签导入 jquery 工作正常,但我正在尝试使用 ES6 语法。

  • 我如何导入 jquery 以满足 semantic-ui 使用 ES6 导入语法?
  • 我应该从 node_modules/ 目录还是我的 dist/ (我复制所有内容的地方)导入?

原文由 Édouard Lopez 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 831
2 个回答

索引.js

 import {$,jQuery} from 'jquery';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;

首先,正如 @nem 在评论中建议的那样,导入应该从 node_modules/ 完成:

那么,从 dist/ 导入是没有意义的,因为这是您的分发文件夹,其中包含生产就绪应用程序。构建您的应用程序应该采用里面的内容 node_modules/ 并将其添加到 dist/ 文件夹,包括 jQuery。

接下来,glob – * as – 是错误的,因为我知道我正在导入什么对象( 例如 jQuery$ --- .

最后,您需要使用 window.$ = $ 将它暴露给其他脚本。

然后,我导入为 $jQuery 以涵盖所有用法, browserify 删除导入重复,所以这里没有开销! ^o^y

原文由 Édouard Lopez 发布,翻译遵循 CC BY-SA 3.0 许可协议

基于 Édouard Lopez 的解决方案,但分为两行:

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

原文由 ha7ilm 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题