如何在浏览器上本地安装babel和使用ES6?

所以,我在这里跟随教程来学习ES2015:

http://k33g.github.io/2015/05/02/ES6.html

但是,我没有find基于该教程的这个文件:

node_modules/babel-core/browser.js 

我在哪里可以得到browser.js? 因为执行后:

 npm install babel-core 

node_modules\babel-core有2个browser.js

 1 node_modules\babel-core\lib\api\register\browser.js 2 node_modules\babel-core\lib\api\browser.js 

我应该复制哪一个?

由于babel 6.2.0 browser.js已被删除。

按照Babel文档 ,你有两个select:

1.使用babel-standalone

它是一个独立的Babel版本,用于非Node.js环境,包括浏览器。 它是babel-browser的替代品,并在官方的Babel repl中使用

2.捆绑你自己的文件:

使用像browserify / webpack这样的打包工具,并直接要求babel-core npm模块,并确保正确configurationbrowserify或webpack以避免由于纯粹的节点依赖性等造成的错误。

configuration使用webpack的例子(我只剩下一个特定的):

 { ... module: { loaders: [ ... { loader: 'json-loader', test: /\.json$/ } ] }, node: { fs: 'empty', module: 'empty', net: 'empty' } } 

然后在你的代码中:

 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] } ) ... 

请注意,代码中需要插件和预设,不能作为string选项传递。

从Babel 6中删除了浏览器内传输,但是Daniel15已经创build了一个独立的版本,可以在“非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"属性。

asynchronous/等待使用babel standalone的例子!

 <!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> 

你需要使用babel-browser软件包中的browser.js : https : //babeljs.io/docs/usage/browser/

最好在服务器端使用编译。