Skip to content
Non-destructive template transformer.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
bin
src
tests
.eslintrc.js
.gitignore
.prettierrc.js
.travis.yml
CHANGELOG.md
LICENSE
README.md
package.json
yarn.lock

README.md

ember-template-recast

APIs

parse

Used to parse a given template string into an AST. Generally speaking, this AST can be mutated and passed into print (docs below).

const templateRecast = require('ember-template-recast');
const template = `
{{foo-bar
  baz="stuff"
}}
`;
let ast = templateRecast.parse(template);
// now you can work with `ast`

print

Used to generate a new template string representing the provided AST.

const templateRecast = require('ember-template-recast');
const template = `
{{foo-bar
  baz="stuff"
}}
`;
let ast = templateRecast.parse(template);
ast.body[0].hash[0].key = 'derp';

templateRecast.print(ast);

    {{foo-bar
      derp="stuff"
    }}

traverse

Used to easily traverse (and possibly mutate) a given template. Returns the resulting AST and the printed template.

The plugin argument has roughly the following interface:

export interface ASTPluginBuilder {
  (env: ASTPluginEnvironment): ASTPlugin;
}

export interface ASTPluginEnvironment {
  meta?: any;
  syntax: Syntax;
}

export interface ASTPlugin {
  name: string;
  visitor: NodeVisitor;
}

export interface Syntax {
  parse: typeof preprocess;
  builders: typeof builders;
  print: typeof print;
  traverse: typeof traverse;
  Walker: typeof Walker;
}

The list of known builders on the env.syntax.builders are found here

Example:

const templateRecast = require('ember-template-recast');
const template = `
{{foo-bar
  baz="stuff"
}}
`;
let { code } = transform(template, env => {
  let { builders: b } = env.syntax;

  return {
    MustacheStatement() {
      return b.mustache(b.path('wat-wat'));
    },
  };
});

console.log(code); // => {{wat-wat}}

Command Line Usage

ember-template-recast comes with a binary for running a transform across multiple files, similar to jscodeshift.

npm install -g ember-template-recast
ember-template-recast directory/of/templates -t transform.js

Example transform plugin:

module.exports = function({ source, path }, { parse, visit }) {
  const ast = parse(source);

  return visit(ast, env => {
    let { builders: b } = env.syntax;

    return {
      MustacheStatement() {
        return b.mustache(b.path('wat-wat'));
      },
    };
  });
};
You can’t perform that action at this time.