I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style.

index.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'));

index.html

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

Project structure

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

package.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}]
    ]
  }

Question

使用classic <script>标记导入jquery很好,但我try 使用ES6语法.

  • How do I import jquery to satisfy semantic-ui using ES6 import syntax?
  • Should I import from the node_modules/ directory or my dist/ (where I copy everything)?

推荐答案

index.js

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

首先,正如@nem在 comments 中所建议的,导入应从node_modules/开始:

Well, importing from dist/ doesn't make sense since that is your distribution folder with production ready app. Building your app should take what's inside node_modules/ and add it to the dist/ folder, jQuery included.

接下来,glob–* as–是错误的,因为我知道要导入什么对象(e.g. jQuery$),所以straigforward import statement可以工作.

最后,您需要使用window.$ = $向其他脚本公开它.

Then, I import as both $ and jQuery to cover all usages, browserify remove import duplication, so no overhead here! ^o^y

Jquery相关问答推荐

在 JavaScript 中解析 URL

jQuery从下拉列表中删除一个选项,给定选项的文本/值

为什么要两次声明 jQuery?

基于垂直滚动的jquery添加/删除类?

延迟后运行功能

具有动态大小图像的马赛克网格 gallery

有没有办法放大 D3 力布局图?

jQuery 判断 是否存在并且有一个值

如何使用 jquery 更改 onclick 事件?

Bootstrap 3.0 弹出框和工具提示

我可以将 Nuget 保留在 jQuery 1.9.x/1.x 路径上(而不是升级到 2.x)吗?

Javascript中的选定文本事件触发器

所有选中复选框的 jQuery 数组(按类)

jQuery:如何从 $.ajax.error 方法中获取 HTTP 状态代码?

带有 jQ​​uery 的饼图

Isotope 和 Masonry jQuery 插件之间的区别

jQuery - 确定输入元素是文本框还是 Select 列表

通过 AJAX MVC 下载 Excel 文件

在某个点停止固定位置滚动?

javascript,是否有像 isArray 这样的 isObject 函数?