ES6 구문을 사용하여 jquery를 가져 오는 방법은 무엇입니까?
트랜스 필러와 플러그인뿐만 아니라 스타일을 ES6
통해 (JavaScript) 구문을 사용하여 새로운 앱을 작성 하고 있습니다.babel
preset-es2015
semantic-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/
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}]
]
}
질문
<script>
가져 오기 위해 클래식 태그를 jquery
사용하는 것이 좋지만 ES6 구문을 사용하려고합니다.
- ES6 가져 오기 구문을 사용
jquery
하기 위해 가져 오려면 어떻게합니까semantic-ui
? node_modules/
디렉토리 또는 내dist/
(모든 것을 복사하는 위치) 에서 가져와야 합니까?
index.js
import {$,jQuery} from 'jquery';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;
먼저 @nem 이 의견에서 제안했듯이 가져 오기는 다음에서 수행해야합니다 node_modules/
.
음, 가져 오기는
dist/
프로덕션 준비 앱이있는 배포 폴더이므로 의미가 없습니다. jQuery를 포함 하여 앱을 빌드node_modules/
하고 내부를 가져 와서dist/
폴더에 추가해야합니다 .
다음으로 glob – * as
–는 내가 가져 오는 객체 ( 예 : jQuery
및 $
)를 알기 때문에 잘못되었습니다 . 따라서 확실한 import 문 이 작동합니다.
마지막으로를 사용하여 다른 스크립트에 노출시켜야합니다 window.$ = $
.
그럼, 모두로 가져 오기 $
및 jQuery
모든 용도를 커버하는, browserify
제거 가져 오기 복제, 그래서 아무 오버 헤드 여기! ^ o ^ y
에두아르 트 로페즈의 솔루션을 바탕으로하지만
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
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.
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': [ '$' ]
// 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};
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');
});
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;
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.
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
webpack users, add the below to your plugins
array.
let plugins = [
// expose $ and jQuery to global scope.
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
];
import {jQuery as $} from 'jquery';
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
Import jquery (I installed with 'npm install jquery@1.9.1')
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.$
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)
참고URL : https://stackoverflow.com/questions/34338411/how-to-import-jquery-using-es6-syntax
'Programming' 카테고리의 다른 글
테스트 목적으로 브라우저에서 CSS를 비활성화하는 방법 (0) | 2020.08.05 |
---|---|
배쉬 평등 연산자 (==, -eq) (0) | 2020.08.05 |
Emacs로 SSH 및 Sudo를 통해 파일 열기 (0) | 2020.08.05 |
작곡가 삭제 변경 : [y, n, v, d, s ,?] (0) | 2020.08.05 |
덮어 쓰기보다는 {% 블록 %}에 추가 할 수 있습니까? (0) | 2020.08.05 |