@a06062125
2016-12-13T18:14:36.000000Z
字数 2874
阅读 374
未分类
Nodejs 的 Api
如果某些代码需要调用Babel的API进行转码,就要使用babel-core模块。返回值为进行过es6语法转译的代码(code), 对应的source map, 以及ast.
var babel = require('babel-core');
// 字符串转码
babel.transform('code();', options);
// => { code, map, ast }
// 文件转码(异步)
babel.transformFile('filename.js', options, function(err, result) {
result; // => { code, map, ast }
});
// 文件转码(同步)
babel.transformFileSync('filename.js', options);
// => { code, map, ast }
// Babel AST转码
babel.transformFromAst(ast, code, options);
// => { code, map, ast }
Babel默认只转换新的JavaScript句法(syntax),而不转换新的API,比如Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise等全局对象,以及一些定义在全局对象上的方法(比如Object.assign)都不会转码。
babel-polyfill
实现了这些API的垫片。
使用方法:在打包文件的入口状况, 引入 babel-polyfill
;
// index.js
import 'babel-polyfill';
// 或者
require('babel-polyfill');
Tips: es5-shim and es5-sham
babel-polyfill已经实现了所有的垫片, 打包过babel-polyfill的业务代码所在的模板页面,不需要再用以下方式引入es5-shim
和es5-sham
<!--[if lte IE 8]>
<script src="/lib/es5-shim.min.js"></script>
<script src="/lib/es5-sham.min.js"></script>
<![endif]-->
Babel command line.
在terminal中使用babel
babel-cli工具自带一个babel-node命令,提供一个支持ES6的REPL环境。它支持Node的REPL(Read-Eval-Print-Loop)环境的所有功能,而且可以直接运行ES6代码。不建议是生产环境使用, 因为所有的转译都是即时的(compiling on the fly)
babel script.js --out-file script-compiled.js --presets=add-module-exports,transform-es2015-modules-amd
gulp-babel
it's transform plugin for browserify
var fs = require("fs");
var browserify = require("browserify");
var babelify = require("babelify");
browserify({ debug: true })
.transform(babelify)
.require("./script.js", { entry: true })
.bundle()
.on("error", function (err) { console.log("Error: " + err.message); })
.pipe(fs.createWriteStream("bundle.js"));
COPY
Babel-types: Babel Types is a Lodash-esque utility library for AST nodes
Babel-register: The require hook will bind itself to node’s require and automatically compile files on the fly.
Babel-template: Generate an AST from a string template
Babel-helpers: Collection of helper functions used by Babel transforms
Babel-code-frame: Generate errors that contain a code frame that point to source locations
可以认为plugins 是为了兼容而做的垫片
a set of Plugins
-- Official Presets
- env (配置更灵活, 可以指定target和浏览器列表)
- latest (按年份集合可用的plugins, 目前包含es2015, es2016, es2017)
- es2017 (async-to-generator, syntax-trailling-function-commas)
- es2016 (exponentiation-operator)
- es2015 (...)
- react
Tips: Presets 和 Plugins 的顺序 :
This means if two transforms both visit the “Program” node, the transforms will run in either plugin or preset order.
- Plugins run before Presets.
- Plugin ordering is first to last.
- Preset ordering is reversed (last to first).
-- Stage-X
(Experimental Presets)
Any transforms in stage-x presets are changes to the language that haven’t been approved to be part of a release of Javascript (such as ES6/ES2015).
慎重使用 stage-0, stage-1;
/*
* @refer https://github.com/css-modules/css-modules
* @refer
*/