Cómo importar jquery usando la sintaxis ES6?


Estoy escribiendo una nueva aplicación usando (JavaScript) ES6 sintaxis a través de babel transpiler y el preset-es2015 plugins, así como semantic-ui para el estilo.

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>

Estructura del proyecto

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

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

Pregunta

Usar la etiqueta classic <script> para importar jquery funciona bien, pero estoy tratando de usar la sintaxis ES6.

  • Cómo puedo importar jquery para satisfacer semantic-ui usando ES6 import la sintaxis?
  • ¿Debo importar desde el directorio node_modules/ o desde mi dist/ (donde copio todo)?
Author: Stephen Docy, 2015-12-17

9 answers

Index.js

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

Primero, como @nem sugirió en el comentario, la importación debe hacerse desde node_modules/:

Bueno, importar desde dist/ no tiene sentido ya que es su carpeta de distribución con la aplicación lista para producción. La creación de su aplicación debe tomar lo que hay dentro de node_modules/ y agregarlo a la carpeta dist/, jQuery incluido.

Luego, el glob –* as– está mal ya que sé qué objeto estoy importando ( e. g. jQuery and $), so a straigforward import statement funcionará.

Por último, necesita exponerlo a otros scripts usando el window.$ = $.

Entonces, importo como $ y jQuery para cubrir todos los usos, browserify eliminar la duplicación de importación, así que no hay sobrecarga aquí! ^o^y

 99
Author: Édouard Lopez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-22 09:57:48

Basado en la solución de Édouard López, pero en dos líneas:

import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
 35
Author: András Retzler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-11 12:00:52

La respuesta aceptada no funcionó para mí
nota: usando rollup js no sé si esta respuesta pertenece aquí
después de
jquery{[8]]} en la costumbre.js

import {$, jQuery} from 'jquery';

O

import {jQuery as $} from 'jquery';

Estaba recibiendo error : Módulo ...node_modules/jquery / dist / jquery.js no exporta jQuery
o
Módulo ...node_modules/jquery / dist / jquery.js no exporta $
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',
};

En lugar de inyección de rollup, probado

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'
};

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

Esto funcionó :
se eliminaron los plugins rollup inject y commonjs

import * as jQuery from 'jquery';

Entonces en costumbre.js

$(function () {
        console.log('Hello jQuery');
});
 7
Author: Ritin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-21 15:43:18

Usuarios de Webpack, agregue lo siguiente a su matriz plugins.

let plugins = [
  // expose $ and jQuery to global scope.
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
];
 4
Author: Muhammad Reda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-20 19:53:13

Importe todo el contenido de jQuery en el ámbito global. Esto inserta $ en el ámbito actual, que contiene todos los enlaces exportados desde jQuery.

import * as $ from 'jquery';

Ahora el belongs pertenece al objeto window.

 3
Author: ivan hertz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-07 02:04:07
import {jQuery as $} from 'jquery';
 1
Author: Farsheed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-17 22:56:26

Si ayuda a alguien, las instrucciones de importación de javascript se izan. Por lo tanto, si una biblioteca tiene una dependencia (por ejemplo, bootstrap) en jquery en el espacio de nombres global (window), esto NO funcionará:

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

Esto se debe a que la importación de bootstrap se eleva y evalúa antes de que jQuery se adjunte a window.

Una forma de evitar esto es no importar jQuery directamente, sino importar un módulo que a su vez importa jQuery Y lo adjunta a la ventana.

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

Donde leaked-jquery se ve como

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

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

 1
Author: craigmichaelmartin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 18:25:19

En primer lugar, instálelos y guárdelos en el paquete.json:

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

En segundo lugar, agregue un alias en la configuración de webpack:

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

Funciona para mí con la última jquery(3.2.1) y jquery-ui(1.12.1).

Ver mi blog para más detalles: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html

 0
Author: cwtuan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-28 14:51:08

Importar jquery (instalé con 'npm install [email protected]')

import 'jquery/jquery.js';

Ponga todo el código que depende de jquery dentro de este método

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

O declarar variable after después de importar

var $ = window.$
 0
Author: Yoseph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-18 19:01:03