如何使用ES6语法导入jQuery?

发布于 2025-01-20 01:53:38 字数 1702 浏览 1 评论 0原文

我正在使用(JavaScript)ES6语法通过Babel Transpiler和PRESET-ES2015插件以及> 语义-UI样式。

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>

项目结构

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

软件包。

  …
  "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}]
    ]
  }

使用

经典&lt; script&gt;标记导入到导入jquery的工作正常,但是我正在尝试使用ES6语法。

  • 如何使用ES6导入语法导入jQuery以满足smantic-ui
  • 我应该从node_modules/目录或我的dist/(在哪里复制所有内容)导入?

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

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

  • 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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

陪你到最终 2025-01-27 01:53:38

index.js

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

首先,如 @nem 在评论中建议的,应从node_modules/中进行导入:

好吧,从dist/导入没有意义,因为那是您的发行文件夹,其中包含生产就绪应用程序。构建您的应用程序应采用node_modules/中的内容,然后将其添加到dist/文件夹中,包括jQuery。

接下来,全球 - * AS - 我知道要导入的对象( eg jquery$ ),所以一个stragforward 会起作用。

最后,您需要使用窗口。$ = $将其公开为其他脚本。

然后,我将同时导入$jQuery要涵盖所有用法,browserify删除导入重复,因此在这里没有开销! ^o^y

index.js

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

First, as @nem suggested in comment, the import should be done from 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.

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

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

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

樱娆 2025-01-27 01:53:38

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

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

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

import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
就此别过 2025-01-27 01:53:38

您可以创建如下所示的模块转换器:

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

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

然后在脚本中使用它:

// script.js
import $ from "./jquery.module.js";
    
$(function(){
  $('body').text('youpi!');
});

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

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

http:// /plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=预览

You can create a module converter like below:

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

This will remove global variables introduced by jQuery (jQuery & $) and export jQuery object as default.

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

ぺ禁宫浮华殁 2025-01-27 01:53:38

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

import * as $ from 'jquery';

现在$属于window对象。

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

import * as $ from 'jquery';

Now the $ belongs to the window object.

青春如此纠结 2025-01-27 01:53:38

如果它对任何人有帮助,javascript import 语句就会被提升。因此,如果一个库在全局命名空间(window)中对jquery有依赖(例如bootstrap),那么这将不起作用:

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

这是因为bootstrap的导入在jQuery附加到window之前被提升和评估。

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

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

其中 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

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:

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.

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.

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

where leaked-jquery looks like

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

桃扇骨 2025-01-27 01:53:38

WebPack用户,将下面添加到您的插件数组中。

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

webpack users, add the below to your plugins array.

let plugins = [
  // expose $ and jQuery to global scope.
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
];
旧人哭 2025-01-27 01:53:38

接受的答案对我不起作用
注意:使用 rollup js 不知道这个答案是否属于这里
之后
npm i --保存 jquery
在 custom.js

import {$, jQuery} from 'jquery';

import {jQuery as $} from 'jquery';

中我收到错误
模块 ...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',
};

而不是汇总注入,尝试

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': [ '

package.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",
  },

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

import * as jQuery from 'jquery';

然后在 custom.js

$(function () {
        console.log('Hello jQuery');
});
] // 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ] 'jQuery': [ '

package.json


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


然后在 custom.js


 ]
},
format: 'cjs' //'iife'
};

package.json

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

然后在 custom.js

The accepted answer did not work for me
note : using rollup js dont know if this answer belongs here
after
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

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': [ '

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

import * as jQuery from 'jquery';

then in custom.js

$(function () {
        console.log('Hello jQuery');
});
] // 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ] 'jQuery': [ '

package.json


This worked :
removed the rollup inject and commonjs plugins


then in custom.js


 ]
},
format: 'cjs' //'iife'
};

package.json

This worked :
removed the rollup inject and commonjs plugins

then in custom.js

简单气质女生网名 2025-01-27 01:53:38

我尚未看到此确切的语法发布,并且在ES6/WebPack环境中对我有用:

import $ from "jquery";

直接从 jQuery的NPM页。希望这对某人有帮助。

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

import $ from "jquery";

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

゛清羽墨安 2025-01-27 01:53:38

皮卡(Pika)是一种CDN,负责提供流行包的模块版本

<script type='module'>
    import * as $ from 'https://cdn.skypack.dev/jquery';

    // use it!
    $('#myDev').on('click', alert);
</script>

Skypack是Pika,因此您也可以使用:import * as $ as $ as $ as $ as $ suf'https://cdn.pika.dev/jquery@jequery@^ 3.5.1'' ;

Pika is a CDN that takes care of providing module versions of popular packages

<script type='module'>
    import * as $ from 'https://cdn.skypack.dev/jquery';

    // use it!
    $('#myDev').on('click', alert);
</script>

Skypack is Pika, so you could also use: import * as $ from 'https://cdn.pika.dev/jquery@^3.5.1';

画▽骨i 2025-01-27 01:53:38

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

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

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

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

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.

万劫不复 2025-01-27 01:53:38
import {jQuery as $} from 'jquery';
import {jQuery as $} from 'jquery';
堇年纸鸢 2025-01-27 01:53:38

我的项目堆栈是: ParcelJS + WordPress

WordPress 本身获得了 jQuery v1.12.4 并且我还导入了 jQuery v3^ 作为其他依赖模块以及 bootstrap/js/dist/collapse 的模块,例如...不幸的是,我不能只留下一个 jQuery 版本,因为其他 WordPress 模块化依赖项。
当然,两个 jquery 版本之间会出现冲突。另请记住,我们为运行 Wordpress(Apache) / ParcelJS (NodeJS) 的项目提供了两种模式,这让一切变得有点困难。因此,在寻找这种冲突的解决方案时,有时项目在左侧崩溃,有时在右侧崩溃。
所以...我的最终解决方案(我希望如此...)是:

    import $ from 'jquery'
    import 'popper.js'
    import 'bootstrap/js/dist/collapse'
    import 'bootstrap/js/dist/dropdown'
    import 'signalr'

    if (typeof window.$ === 'undefined') {
        window.$ = window.jQ = $.noConflict(true);
    }

    if (process) {
        if (typeof window.jQuery === 'undefined') {
            window.$ = window.jQuery = $.noConflict(true);
        }
    }

    jQ('#some-id').do('something...')    

    /* Other app code continuous below.......... */

我仍然不明白自己是如何做到的,但这种方法有效。两个 jQuery 版本的错误和冲突不再出现

My project stack is: ParcelJS + WordPress

WordPress got jQuery v1.12.4 itself and I have also import jQuery v3^ as module for other depending modules as well as bootstrap/js/dist/collapse, for example... Unfortunately, I can’t leave only one jQuery version due to other WordPress modular dependencies.
And ofcourse there is conflict arises between two jquery version. Also keep in mind we got two modes for this project running Wordpress(Apache) / ParcelJS (NodeJS), witch make everything little bit difficulty. So at solution for this conflict was searching, sometimes the project broke on the left, sometimes on the right side.
SO... My finall solution (I hope it so...) is:

    import $ from 'jquery'
    import 'popper.js'
    import 'bootstrap/js/dist/collapse'
    import 'bootstrap/js/dist/dropdown'
    import 'signalr'

    if (typeof window.$ === 'undefined') {
        window.$ = window.jQ = $.noConflict(true);
    }

    if (process) {
        if (typeof window.jQuery === 'undefined') {
            window.$ = window.jQuery = $.noConflict(true);
        }
    }

    jQ('#some-id').do('something...')    

    /* Other app code continuous below.......... */

I still didn’t understand how myself, but this method works. Errors and conflicts of two jQuery version no longer arise

燃情 2025-01-27 01:53:38
import $ from 'jquery'

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

// export for others scripts to use
window.$ = window.jQuery = $
始终不够爱げ你 2025-01-27 01:53:38

接受的答案显示了如何静态导入jQuery。

但是,jQuery是一个大包装,我们通常只想在需要时加载。因此,为了完整性,以下是在功能中动态加载jQuery的方法:

async function showStatus(statusMessage) {
    if (typeof window.jQuery === 'undefined') {
        window.jQuery = await import('jquery').default;
        window.$ = window.jQuery;
    } 

    jQuery('#status').html(statusMessage);
}

The accepted answer shows how to import jQuery statically.

However, jQuery is a big package and we often want to load only if or when it's needed. So, for completeness, here's how to load jQuery dynamically e.g. within a function:

async function showStatus(statusMessage) {
    if (typeof window.jQuery === 'undefined') {
        window.jQuery = await import('jquery').default;
        window.$ = window.jQuery;
    } 

    jQuery('#status').html(statusMessage);
}
明月夜 2025-01-27 01:53:38

首先,安装并将它们保存在 package.json 中:

npm i --save jquery
npm i --save jquery-ui-dist

其次,在 webpack 配置中添加别名:

resolve: {
  root: [
    path.resolve(__dirname, '../node_modules'),
    path.resolve(__dirname, '../src'),
  ],
  alias: {
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
  },
  extensions: ['', '.js', '.json'],
}

它对我来说适用于最后一个 jquery(3.2.1) 和 jquery-ui(1.12.1)。

有关详细信息,请参阅我的博客: http: //code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html

First of all, install and save them in package.json:

npm i --save jquery
npm i --save jquery-ui-dist

Secondly, add a alias in webpack configuration:

resolve: {
  root: [
    path.resolve(__dirname, '../node_modules'),
    path.resolve(__dirname, '../src'),
  ],
  alias: {
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
  },
  extensions: ['', '.js', '.json'],
}

It work for me with the last jquery(3.2.1) and jquery-ui(1.12.1).

See my blog for detail: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html

烧了回忆取暖 2025-01-27 01:53:38

continue

Import jquery (I installed with 'npm install [email protected]')

import 'jquery/jquery.js';

Put all your code that depends on jquery inside this method

+function ($) { 
    // your code
}(window.jQuery);

or declare variable $ after import

var $ = window.$
雅心素梦 2025-01-27 01:53:38

我想使用 alread-buildy jQuery(来自 jquery.org),但这里提到的所有解决方案都不起作用,我解决此问题的方法是添加以下几行,这应该使其适用于几乎所有环境:

 export default  ( typeof module === 'object' && module.exports && typeof module.exports.noConflict === 'function' )
    ? module.exports.noConflict(true)
    : ( typeof window !== 'undefined' ? window : this ).jQuery.noConflict(true)

I wanted to use the alread-buildy jQuery (from jquery.org) and all the solutions mentioned here didn't work, how I fixed this issue was adding the following lines which should make it work on nearly every environment:

 export default  ( typeof module === 'object' && module.exports && typeof module.exports.noConflict === 'function' )
    ? module.exports.noConflict(true)
    : ( typeof window !== 'undefined' ? window : this ).jQuery.noConflict(true)
天赋异禀 2025-01-27 01:53:38

你可以这样导入

import("jquery").then((jQuery) => {
  window.$ = jQuery;
  window.jQuery = jQuery;
  import("bootstrap").then((_bs)=>{
    $(function() {});
  })
});

You can import like this

import("jquery").then((jQuery) => {
  window.$ = jQuery;
  window.jQuery = jQuery;
  import("bootstrap").then((_bs)=>{
    $(function() {});
  })
});
口干舌燥 2025-01-27 01:53:38

如果您使用的是WebPack 4,答案是使用supplyplugin。他们的 documentation> documentation> documentation> documentation of jquerar.js jquery.js A>用例:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

问题是,使用import语法angular.js和jQuery时,将始终导入在您有机会将jQuery分配给window.jquery.jquery(import> import)之前。语句无论在代码中何处都将首先运行!)。这意味着Angular将始终看到窗口。jQuery as Undefined直到您使用supplyplugin

If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文