Add support for preserving comments in babel-template. (#3689)

* Add support for preserving comments in babel-template.

* Add an API section to babel-template.
This commit is contained in:
Ben Briggs
2016-09-01 15:50:25 +01:00
committed by Henry Zhu
parent 23ea626241
commit c94abcc170
5 changed files with 74 additions and 20 deletions

View File

@@ -32,3 +32,33 @@ console.log(generate(ast).code);
```js
var myModule = require('my-module');
```
## API
### `template(code, [opts])`
#### code
Type: `string`
#### options
`babel-template` accepts all of the options from [babylon], and specifies
some defaults of its own:
* `allowReturnOutsideFunction` is set to `true` by default.
* `allowSuperOutsideMethod` is set to `true` by default.
##### preserveComments
Type: `boolean`
Default: `false`
Set this to `true` to preserve any comments from the `code` parameter.
#### Return value
`babel-template` returns a `function` which is invoked with an optional object
of replacements. See the usage section for an example.
[babylon]: https://github.com/babel/babylon#options

View File

@@ -24,16 +24,19 @@ export default function (code: string, opts?: Object): Function {
}
}
opts = assign({
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
preserveComments: false,
}, opts);
let getAst = function () {
let ast;
try {
ast = babylon.parse(code, assign({
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true
}, opts));
ast = babylon.parse(code, opts);
ast = traverse.removeProperties(ast);
ast = traverse.removeProperties(ast, {preserveComments: opts.preserveComments});
traverse.cheap(ast, function (node) {
node[FROM_TEMPLATE] = true;

View File

@@ -1,6 +1,9 @@
var generator = require('../../babel-generator').default;
var template = require("../lib");
var chai = require("chai");
var comments = "// Sum two numbers\nconst add = (a, b) => a + b;";
suite("templating", function () {
test("import statement will cause parser to throw by default", function () {
chai.expect(function () {
@@ -13,4 +16,15 @@ suite("templating", function () {
template("import foo from 'foo'", {sourceType: 'module'})({});
}).not.to.throw();
});
test("should strip comments by default", function () {
var code = "const add = (a, b) => a + b;"
var output = template(comments)();
chai.expect(generator(output).code).to.be.equal(code);
});
test("should preserve comments with a flag", function () {
var output = template(comments, {preserveComments: true})();
chai.expect(generator(output).code).to.be.equal(comments);
});
});