简体   繁体   English

我怎样才能使用ES6从npm包导入jQuery?

[英]How could I import jQuery from npm package using ES6 only?

I installed jQuery with npm -install jquery and it created a node_modules folder in my project with jquery in it. 我用npm -install jquery安装了jQuery,它在我的项目中用jquery创建了一个node_modules文件夹。 But when I try to import it using ES6 import it gives me an error. 但是当我尝试使用ES6导入导入它时,它给了我一个错误。

I don't want to use Webpack or require() and have to compile it... anything else just plain vanilla ES6. 我不想使用Webpack或require()并且必须编译它......其他任何东西只是简单的vanilla ES6。

I'm always gettting this error 我总是得到这个错误

Uncaught SyntaxError: The requested module './node_modules/jquery/dist/jquery.min.js' does not provide an export named '$' 未捕获的SyntaxError:请求的模块'./node_modules/jquery/dist/jquery.min.js'不提供名为'$'的导出

or 要么

Uncaught SyntaxError: The requested module './node_modules/jquery/src/jquery.js' does not provide an export named '$' 未捕获的SyntaxError:请求的模块'./node_modules/jquery/src/jquery.js'不提供名为'$'的导出

Project structure 项目结构

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

app.js app.js

import { $ } from './node_modules/jquery/dist/jquery.min.js'; // <-- does not work
import { $ } from './node_modules/jquery/src/jquery.js'; // <-- does not work
window.$ = $;

$('body').css('background-color', 'red')

尝试npm install jquery然后import $ from "jquery"

At the moment, this functionality is only beginning to be supported by browsers. 目前,这项功能才开始受到浏览器的支持。 Full implementation is provided in many transpilers such as TypeScript and Babel, and bundlers such as Webpack. 许多转换器(如TypeScript和Babel)以及捆绑器(如Webpack)都提供了完整的实现。

ES6 modules have been fully supported in Chrome since version 65 but it still throws errors if we try and use the import/export keywords to import or export modules in JavaScript files. 从版本65开始,Chrome完全支持ES6模块,但如果我们尝试使用导入/导出关键字导入或导出JavaScript文件中的模块,它仍会引发错误。

So what do you have to do to make ES6 modules work without Webpack/Browserify/Babel is to add next script tag in your index.html file: 那么,如果没有Webpack / Browserify / Babel使ES6模块工作,你需要做什么才能在index.html文件中添加下一个脚本标记:

<script type="module" src="ES6-Node.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM