[英]JS: enabling export/import on client side (ES6 or using babel)?
我想在应用程序目录中导出/导入本地文件:
我的index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<script type="text/babel" src="main.js"></script>
</body>
</html>
actions.js
:
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'
main.js
(从 index.html 加载):
import {ADD_TODO, TOGGLE_TODO, SET_VISIBILITY_FILTER} from 'actions'
现在,如果我在没有 babel 的情况下使用 javascript,我将得到:
Uncaught SyntaxError: Unexpected token import
我使用Chrome 浏览器版本 60 。 这个版本不应该已经支持 ES6 了吗? 通过支持,我应该能够使用导出/导入?
我也尝试过使用 babel(使用从index.html
加载的独立 babel)。
然后我得到这个错误:
Uncaught ReferenceError: require is not defined
at <anonymous>:4:16
at n (https://unpkg.com/babel-standalone@6.15.0/babel.min.js:12:27049)
at r (https://unpkg.com/babel-standalone@6.15.0/babel.min.js:12:27558)
at e.src.i.(anonymous function).error (https://unpkg.com/babel-standalone@6.15.0/babel.min.js:12:27873)
at XMLHttpRequest.i.onreadystatechange (https://unpkg.com/babel-standalone@6.15.0/babel.min.js:12:27316)
我知道客户端不存在require
,但不是 ES6 的导出/导入(不是 NodeJS 导出)语法吗?
我是否需要求助于webpack
类的东西才能工作?
根据这个答案: Trying ES6 imports with Chrome 但它似乎不起作用,您需要在 Chrome 中启用Experimental Web Platform
标志并使用<script type="module" src="main.js"></script>
。 但是使用它,停止加载任何东西。 似乎浏览器只是忽略了这种类型。 即使这种方法可行,那么我想我也无法使用 babel,因为它会使用不同的类型?
PS据此:http: //2ality.com/2014/09/es6-modules-final.html#named-exports-several-per-module它应该可以工作..
现在90% 以上的浏览器都支持import
/ export
语句,并将在未来继续使用( 请参阅此 SO 问题)。
在模块 (myModule.js) 中:
const myVar = 'Hello !!';
export {
myVar
}
在 index.html 中
<script type="module">
import myVar from './myModule.js'
console.log(myVar) // output 10
</script>
Chrome 已经实现了 es6 的大部分新特性,除了import / export
还没有实现,更多细节: https ://ruanyf.github.io/es-checker/
如果你不想使用 webpack 编译文件,试试:
$ npm install --global babel-cli
接着:
babel example.js -o compiled.js
最后,你会得到编译后的文件,这些文件将支持浏览器。
另外,关键字require/exports/module.exports
是 CommonJS 规范,由 Node.js 支持。文件https://unpkg.com/babel-standalone@6.15.0/babel.min.js
使用了 CommonJS 规范,所以会在浏览器端报错
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.