babel-template

raw JSON →
6.26.0 verified Sat Apr 25 auth: no javascript deprecated

Generate an AST from a string template (quasiquote implementation). Current stable version is 6.26.0 (legacy Babel 6). Release cadence: infrequent; part of Babel monorepo, which has moved on to v7/v8. Key differentiator: allows building AST nodes using template syntax instead of manual node construction, but only works with Babel 6 AST types. For Babel 7+, use @babel/template instead.

error Cannot find module 'babel-template'
cause Package not installed or wrong package name (e.g., Babel 7+ users might try to use this instead of @babel/template).
fix
Run 'npm install --save-dev babel-template' for Babel 6, or use '@babel/template' for Babel 7+.
error TypeError: template is not a function
cause Incorrect import attempt, e.g., import { template } from 'babel-template'.
fix
Use default import: import template from 'babel-template'.
deprecated babel-template is only compatible with Babel 6. For Babel 7+, use @babel/template.
fix Migrate to @babel/template: npm install @babel/template --save-dev and update imports to import template from '@babel/template'.
gotcha Template placeholders (e.g., IMPORT_NAME) must be valid JavaScript identifiers and must appear in the template exactly as they are used (case-sensitive).
fix Ensure placeholders are all uppercase or follow identifier rules; avoid using keywords.
gotcha babel-template relies on babylon (Babel 6 parser) which does not support all modern JavaScript syntax (e.g., optional chaining, nullish coalescing).
fix Use @babel/template with @babel/parser for modern syntax support.
npm install babel-template
yarn add babel-template
pnpm add babel-template

Shows how to create a template function using babel-template and invoke it with AST node replacements.

import template from 'babel-template';
import generate from 'babel-generator';
import * as t from 'babel-types';

const buildRequire = template(`
  var IMPORT_NAME = require(SOURCE);
`);

const ast = buildRequire({
  IMPORT_NAME: t.identifier('myModule'),
  SOURCE: t.stringLiteral('my-module')
});

console.log(generate(ast).code);
// var myModule = require('my-module');