Javascript 如何使用 ES6 语法导入 jquery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34338411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:11:09  来源:igfitidea点击:

How to import jquery using ES6 syntax?

javascriptjqueryecmascript-6browserifysemantic-ui

提问by édouard Lopez

I'm writing a new app using (JavaScript) ES6syntax through babeltranspiler and the preset-es2015plugins, as well as semantic-uifor the style.

我正在ES6通过babel转译器和preset-es2015插件以及semantic-ui样式使用(JavaScript)语法编写一个新应用程序。

index.js

索引.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

索引.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

包.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

Using classic <script>tag to import jqueryworks fine, but I'm trying to use the ES6 syntax.

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

  • How do I import jqueryto satisfy semantic-uiusing ES6 import syntax?
  • Should I import from the node_modules/directory or my dist/(where I copy everything)?
  • 如何导入jquery以满足semantic-ui使用 ES6 导入语法?
  • 我应该从node_modules/目录导入还是从我的dist/(我复制所有内容的地方)导入?

回答by édouard Lopez

index.js

索引.js

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

First, as @nemsuggested in comment, the import should be done from node_modules/:

首先,正如@nem在评论中建议的那样,导入应该从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.

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

Next, the glob –* as– is wrong as I know what object I'm importing (e.g.jQueryand $), so a straigforward import statementwill work.

接下来,glob – * as– 是错误的,因为我知道我正在导入什么对象(例如jQueryand $),所以直接导入语句将起作用。

Last you need to expose it to other scripts using the window.$ = $.

最后,您需要使用window.$ = $.

Then, I import as both $and jQueryto cover all usages, browserifyremove import duplication, so no overhead here! ^o^y

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

回答by ha7ilm

Based on the solution of édouard Lopez, but in two lines:

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

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

回答by ivan hertz

Import the entire JQuery's contents in the Global scope. This inserts $ into the current scope, containing all the exported bindings from the JQuery.

在全局范围内导入整个 JQuery 的内容。这会将 $ 插入当前范围,包含从 JQuery 导出的所有绑定。

import * as $ from 'jquery';

Now the $ belongs to the window object.

现在 $ 属于 window 对象。

回答by Yukulélé

You can create a module converter like below:

您可以创建一个模块转换器,如下所示:

// jquery.module.js
import 'https://code.jquery.com/jquery-3.3.1.min.js'
export default window.jQuery.noConflict(true)

This will remove global variables introduced by jQuery and export jQuery object as default.

这将删除 jQuery 引入的全局变量并默认导出 jQuery 对象。

Then use it in your script:

然后在你的脚本中使用它:

// script.js
import $ from "./jquery.module.js";

$(function(){
  $('body').text('youpi!');
});

Do not forget to load it as a module in your document:

不要忘记将其作为模块加载到文档中:

<script type='module' src='./script.js'></script>

http://plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=preview

http://plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=preview

回答by Ritin

The accepted answer did not work for me
note : using rollup jsdont know if this answer belongs here
after
npm i --save jquery
in custom.js

接受的答案对我不起作用
注意:使用 rollup js不知道

npm i --save jquery
in custom.js之后这个答案是否属于这里

import {$, jQuery} from 'jquery';

or

或者

import {jQuery as $} from 'jquery';

i was getting error: Module ...node_modules/jquery/dist/jquery.js does not export jQuery
or
Module ...node_modules/jquery/dist/jquery.js does not export $
rollup.config.js

我收到错误:模块 ...node_modules/jquery/dist/jquery.js 不导出jQuery

模块 ...node_modules/jquery/dist/jquery.js 不导出$
rollup.config.js

export default {
    entry: 'source/custom',
    dest: 'dist/custom.min.js',
    plugins: [
        inject({
            include: '**/*.js',
            exclude: 'node_modules/**',
            jQuery: 'jquery',
            // $: 'jquery'
        }),
        nodeResolve({
            jsnext: true,
        }),
        babel(),
        // uglify({}, minify),
    ],
    external: [],
    format: 'iife', //'cjs'
    moduleName: 'mycustom',
};

instead of rollup inject, tried

而不是汇总注入,尝试

commonjs({
   namedExports: {
     // left-hand side can be an absolute path, a path
     // relative to the current directory, or the name
     // of a module in node_modules
     // 'node_modules/jquery/dist/jquery.js': [ '$' ]
     // 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
        'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};

package.json

包.json

  "devDependencies": {
    "babel-cli": "^6.10.1",
    "babel-core": "^6.10.4",
    "babel-eslint": "6.1.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-external-helpers": "6.18.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-register": "6.9.0",
    "eslint": "2.12.0",
    "eslint-config-airbnb-base": "3.0.1",
    "eslint-plugin-import": "1.8.1",
    "rollup": "0.33.0",
    "rollup-plugin-babel": "2.6.1",
    "rollup-plugin-commonjs": "3.1.0",
    "rollup-plugin-inject": "^2.0.0",
    "rollup-plugin-node-resolve": "2.0.0",
    "rollup-plugin-uglify": "1.0.1",
    "uglify-js": "2.7.0"
  },
  "scripts": {
    "build": "rollup -c",
  },

This worked :
removed the rollup inject and commonjs plugins

这有效:
删除了汇总注入和 commonjs 插件

import * as jQuery from 'jquery';

then in custom.js

然后在 custom.js

$(function () {
        console.log('Hello jQuery');
});

回答by Muhammad Reda

webpack users, add the below to your pluginsarray.

webpack 用户,将以下内容添加到您的plugins数组中。

let plugins = [
  // expose $ and jQuery to global scope.
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
];

回答by craigmichaelmartin

If it helps anyone, javascript import statements are hoisted. Thus, if a library has a dependency (eg bootstrap) on jquery in the global namespace (window), this will NOT work:

如果它对任何人有帮助,就会提升 javascript 导入语句。因此,如果一个库在全局命名空间(窗口)中对 jquery 有依赖(例如引导程序),这将不起作用:

import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
import 'bootstrap/dist/js/bootstrap.min';

This is because the import of bootstrap is hoisted and evaluated before jQuery is attached to window.

这是因为在 jQuery 附加到窗口之前,引导程序的导入被提升和评估。

One way to get around this is to not import jQuery directly, but instead import a module which itself imports jQuery AND attaches it to the window.

解决此问题的一种方法是不直接导入 jQuery,而是导入一个模块,该模块本身导入 jQuery 并将其附加到窗口。

import jQuery from './util/leaked-jquery';
import 'bootstrap/dist/js/bootstrap.min';

where leaked-jquerylooks like

哪里leaked-jquery看起来像

import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
export default $;
export jQuery;

EG, https://github.com/craigmichaelmartin/weather-app--birch/blob/4d9f3b03719e0a2ea3fb5ddbbfc453a10e9843c6/javascript/util/leak_jquery.js

EG,https://github.com/craigmichaelmartin/weather-app--birch/blob/4d9f3b03719e0a2ea3fb5ddbbfc453a10e9843c6/javascript/util/leak_jquery.js

回答by Stephen Shank

I did not see this exact syntax posted yet, and it worked for me in an ES6/Webpack environment:

我还没有看到这个确切的语法发布,它在 ES6/Webpack 环境中对我有用:

import $ from "jquery";

Taken directly from jQuery's NPM page. Hope this helps someone.

直接取自jQuery 的 NPM 页面。希望这可以帮助某人。

回答by VNN456

If you are not using any JS build tools/NPM, then you can directly include Jquery as:

如果您没有使用任何 JS 构建工具/NPM,那么您可以直接将 Jquery 包含为:

import  'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;

You may skip import(Line 1) if you already included jquery using script tag under head.

如果您已经在 head 下使用 script 标签包含了 jquery,则可以跳过导入(第 1 行)。

回答by Farsheed

import {jQuery as $} from 'jquery';