ES6 구문을 사용하여 jquery를 가져오는 방법은 무엇입니까?
(자바스크립트)를 사용하여 새로운 앱을 작성하고 있습니다.ES6
에서 구한문까지.babel
와 트파일와그러스랜▁trans.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'));
색인.
<!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}]
]
}
질문.
클식사 사용<script>
가올태그를 합니다.jquery
잘 작동하지만 ES6 구문을 사용하려고 합니다.
- 을 가져오는
jquery
만족시키기 위해semantic-ui
ES6 가져오기 구문을 사용하시겠습니까? - 에서 ?
node_modules/
나의 디토리내는또.dist/
(모든 내용을 복사할 수 있는 위치)?
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
어떤 개체를 가져오는지 알고 있기 때문에 잘못된 것입니다(예: jQuery
그리고.$
), 따라서 간단한 가져오기 문이 작동합니다.
으로 막으로다사용다른스합노니출다야해크에트립마를 하여 다른 .window.$ = $
.
그럼, 저는 둘 다 수입합니다.$
그리고.jQuery
모든 용도로 사용할 수 있습니다.browserify
가져오기 복제를 제거하여 오버헤드가 없습니다! ^o^y
에두아르 로페즈의 솔루션을 기반으로 하지만 다음 두 줄로 나뉩니다.
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
아래와 같은 모듈 컨버터를 만들 수 있습니다.
// 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=preview
전역 범위에서 전체 JQuery의 내용을 가져옵니다.그러면 JQuery에서 내보낸 모든 바인딩이 포함된 $가 현재 범위에 삽입됩니다.
import * as $ from 'jquery';
이제 $는 창 개체에 속합니다.
도움이 될 경우 javascript 가져오기 문이 표시됩니다.따라서 라이브러리가 글로벌 네임스페이스(윈도우)의 jquery에 대한 종속성(예: 부트스트랩)을 가지고 있다면, 이것은 작동하지 않을 것입니다.
import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
import 'bootstrap/dist/js/bootstrap.min';
이는 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
.
참고: 롤업을 사용하는 js는 이 답변이 여기에 해당되는지 알 수 없습니다.
--jquery ㅠㅠ
커스텀.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': [ '$' ]
// 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};
꾸러미제이손
"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",
},
이것은 효과가 있었습니다.
및 했습니다.
import * as jQuery from 'jquery';
그런 다음 커스텀.js.
$(function () {
console.log('Hello jQuery');
});
을 당신의 팩사용자, 아을내추합에 추가하세요."에하세요.plugins
vmdk
let plugins = [
// expose $ and jQuery to global scope.
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
];
아직 정확한 구문이 게시되지 않았으며 ES6/Webpack 환경에서 작동했습니다.
import $ from "jquery";
jQuery의 NPM 페이지에서 직접 가져온 것입니다.이것이 누군가에게 도움이 되기를 바랍니다.
JS 빌드 도구/NPM을 사용하지 않는 경우 다음과 같이 Jquery를 직접 포함할 수 있습니다.
import 'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;
머리글 아래에 스크립트 태그를 사용하여 jquery를 이미 포함한 경우 가져오기(라인 1)를 건너뛸 수 있습니다.
Pika는 인기 있는 패키지의 모듈 버전을 제공하는 CDN입니다.
<script type='module'>
import * as $ from 'https://cdn.skypack.dev/jquery';
// use it!
$('#myDev').on('click', alert);
</script>
Skypack은 Pika이므로 다음을 사용할 수도 있습니다.import * as $ from 'https://cdn.pika.dev/jquery@^3.5.1';
import {jQuery as $} from 'jquery';
내 프로젝트 스택은 다음과 같습니다: ParcelJS + WordPress
WordPress는 jQuery v1.12.4 자체를 얻었으며, 저는 또한 jQuery v3^을 다른 종속 모듈을 위한 모듈로 가져왔습니다.bootstrap/js/dist/collapse
예를 들면...안타깝게도 다른 WordPress 모듈 종속성 때문에 jQuery 버전을 하나만 남길 수 없습니다.그리고 물론 두 개의 jquery 버전 사이에 충돌이 발생합니다.또한 이 프로젝트에는 워드프레스(아파치)/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 버전의 오류 및 충돌이 더 이상 발생하지 않습니다.
import $ from 'jquery'
// export for others scripts to use
window.$ = window.jQuery = $
먼저 패키지에 설치하고 저장합니다.json:
npm i --save jquery
npm i --save jquery-ui-dist
두 번째로 웹 팩 구성에 별칭을 추가합니다.
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
jquery 가져오기('npm install jquery@1.9.1'로 설치)
import 'jquery/jquery.js';
jquery에 의존하는 모든 코드를 이 메서드 안에 넣습니다.
+function ($) {
// your code
}(window.jQuery);
또는 가져오기 후 변수 $ 선언
var $ = window.$
이미 빌드된 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)
다음과 같이 가져올 수 있습니다.
import("jquery").then((jQuery) => {
window.$ = jQuery;
window.jQuery = jQuery;
import("bootstrap").then((_bs)=>{
$(function() {});
})
});
만약 당신이 웹팩 4를 사용하고 있다면, 답은 다음과 같습니다.ProvidePlugin
이 문서는 jquery 사용 사례를 포함한 angular.js에 대해 자세히 설명합니다.
new webpack.ProvidePlugin({
'window.jQuery': 'jquery'
});
는 문는사때할을 사용할 입니다.import
구문 angular.js 및 jquery는 항상 창에 jquery를 할당하기 전에 가져옵니다.jQuery(import
명령문은 코드의 위치에 관계없이 항상 먼저 실행됩니다!).이것은 각도가 항상 창을 볼 수 있다는 것을 의미합니다.사할때까정의않은지되 jQuery를 할 때까지 쿼리ProvidePlugin
.
언급URL : https://stackoverflow.com/questions/34338411/how-to-import-jquery-using-es6-syntax
'it-source' 카테고리의 다른 글
각 Kotlin에 대한 현재 인덱스를 가져오는 방법 (0) | 2023.08.24 |
---|---|
문자열을 통해 PowerShell에서 함수 호출 (0) | 2023.08.24 |
스프링 배치 프레임워크 - 배치 테이블 자동 생성 (0) | 2023.08.24 |
구성 블록과 일치하는 다중 행 정규식 (0) | 2023.08.24 |
모든 Ajax 호출 후 Google 차트 다시 그리기 (0) | 2023.08.24 |