所以,我正在按照教程学习ES2015:
http://k33g.github.io/2015/05/02/ES6.html
但是,我找不到基于该教程的文件:
node_modules/babel-core/browser.js
Run Code Online (Sandbox Code Playgroud)
我在哪里可以获得browser.js?因为我执行后:
npm install babel-core
Run Code Online (Sandbox Code Playgroud)
有2个browser.js node_modules\babel-core
1 node_modules\babel-core\lib\api\register\browser.js
2 node_modules\babel-core\lib\api\browser.js
Run Code Online (Sandbox Code Playgroud)
我应该复制哪一个?
由于babel6.2.0 browser.js已被删除.
在Babel文档之后,您有两个选择:
1.使用babel-standalone:
它是Babel的独立版本,用于非Node.js环境,包括浏览器.它是babel-browser官方Babel repl的替代和使用
2.捆绑您自己的文件:
使用像browserify/webpack这样的捆绑器并直接需要babel-corenpm模块,并确保正确配置browserify或webpack以避免由于纯节点依赖性等导致的错误.
使用webpack的配置示例(我只留下了一个特定的):
{
...
module: {
loaders: [
...
{
loader: 'json-loader',
test: /\.json$/
}
]
},
node: {
fs: 'empty',
module: 'empty',
net: 'empty'
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中:
import {transform} from 'babel-core';
import es2015 from 'babel-preset-es2015';
import transformRuntime from 'babel-plugin-transform-runtime';
...
transform(
/* your ES6 code */,
{
presets: [es2015],
plugins: [transformRuntime]
}
)
...
Run Code Online (Sandbox Code Playgroud)
请注意,代码中需要插件和预设,不能作为字符串选项传递.
已经从Babel 6中删除了浏览器内的转换,但Daniel15创建了一个独立的构建,用于"非Node.js环境,包括浏览器":
https://github.com/Daniel15/babel-standalone
您需要做的就是将此引用添加到您的页面:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.4.4/babel.min.js"></script>
然后确保script type="text/babel"在引用其他脚本文件时使用该属性.
使用babel独立的async/await示例!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Standalone Async/Await Example</h1>
<!-- Load Babel -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.14.0/babel.min.js"></script>
<script type="text/babel" data-presets="es2017, stage-3" data-plugins="syntax-async-functions">
/* Output of Babel object */
console.log('Babel =', Babel);
var users = { '123' : { name : 'Joe Montana'} };
process();
async function process()
{
var id = await getId();
console.log("User ID: "+id);
var name = await getUserName(id);
console.log("User Name: "+name);
}
function getId()
{
return new Promise((resolve, reject) => {
setTimeout(() => { console.log('calling'); resolve("123"); }, 2000);
});
}
function getUserName(id)
{
return new Promise((resolve, reject) => {
setTimeout(() => { console.log('requesting user name with id: '+id); resolve(users[id].name); }, 3000);
});
}
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19349 次 |
| 最近记录: |