How to use babel-template - 10 common examples

To help you get started, we’ve selected a few babel-template examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github babel / kneden / src / looprefactor.js View on Github external
// .then(function (_resp) {
    //   _temp = _resp;
    //   if (_temp !== _recursive) {
    //     return _temp;
    //   }
    // });
    if (info.addReturnHandler) {
      var tmp = identifier(path.scope.generateUid('temp'));
      addVarDecl(tmp);
      path.node.loopLabel = label;
      path.replaceWithMultiple(loopReturnHandler({TMP: tmp, BASE: path.node, FUNC: functionID}));
    }
  });
}

const loopReturnHandler = template(`
  TMP = BASE
  if (_temp !== FUNC) {
    return _temp;
  }
`);

const continueStatementEquiv = funcID => {
  // continue label; -> return await label();
  const stmt = returnStatement(awaitExpression(callExpression(funcID, [])))
  // not a 'real' return
  stmt.noHandlerRequired = true;
  return stmt;
};

const BreakContinueReplacementVisitor = extend({
  ReturnStatement(path) {
github babel / babel / packages / babel-core / src / tools / build-external-helpers.js View on Github external
/* eslint max-len: 0 */

import * as helpers from "babel-helpers";
import generator from "babel-generator";
import * as messages from "babel-messages";
import template from "babel-template";
import each from "lodash/collection/each";
import * as t from "babel-types";

let buildUmdWrapper = template(`
  (function (root, factory) {
    if (typeof define === "function" && define.amd) {
      define(AMD_ARGUMENTS, factory);
    } else if (typeof exports === "object") {
      factory(COMMON_ARGUMENTS);
    } else {
      factory(BROWSER_ARGUMENTS);
    }
  })(UMD_ROOT, function (FACTORY_PARAMETERS) {
    FACTORY_BODY
  });
`);

function buildGlobal(namespace, builder) {
  let body      = [];
  let container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
github liferay / liferay-js-toolkit / packages / babel-plugin-wrap-modules-amd / src / index.js View on Github external
/**
 * © 2017 Liferay, Inc. 
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

import template from 'babel-template';
import fs from 'fs';
import * as babelIpc from 'liferay-npm-build-tools-common/lib/babel-ipc';
import PluginLogger from 'liferay-npm-build-tools-common/lib/plugin-logger';

const buildDefine = template(`
     define(DEPS, function(module, exports, require) {
        // Make module believe it is running under Node.js
        var define = undefined;
 	    SOURCE
     })
 `);

/**
 * @return {object} a babel visitor
 */
export default function({types: t}) {
	const wrapVisitor = {
		Identifier(path, state) {
			const {node} = path;
			const {dependencies} = state;
			const {log} = babelIpc.get(state, () => ({
github dtinth / babel-plugin-__coverage__ / src / index.js View on Github external
'use strict'
// babel-plugin-__coverage__
//
// This is my first Babel plugin, and I wrote it during the night.
// Therefore, be prepared to see a lot of copypasta and wtf code.

import { util } from 'babel-core'
import template from 'babel-template'
import nameFunction from 'babel-helper-function-name'
import { realpathSync } from 'fs'
import { createHash } from 'crypto'

const coverageTemplate = template(`
  var FILE_COVERAGE
  function COVER () {
    if (!FILE_COVERAGE) FILE_COVERAGE = GET_INITIAL_FILE_COVERAGE()
    return FILE_COVERAGE
  }
  function GET_INITIAL_FILE_COVERAGE () {
    var path = PATH, hash = HASH
    var global = (new Function('return this'))()
    var coverage = global['__coverage__'] || (global['__coverage__'] = { })
    if (coverage[path] && coverage[path].hash === hash) return coverage[path]
    var coverageData = global['JSON'].parse(INITIAL)
    coverageData.hash = hash
    return coverage[path] = coverageData
  }
  COVER ()
`)
github finom / babel-plugin-transform-es2015-modules-simple-amd / src / index.js View on Github external
import 'better-log/install';
import template from "babel-template";

let buildModule = template(`
define([IMPORT_PATHS], function(IMPORT_VARS) {
	NAMED_IMPORTS;
	BODY;
});
`);

module.exports = function({ types: t }) {
	return {
		visitor: {
			Program: {
				exit(path, file) {
					let body = path.get("body"),
						sources = [],
						anonymousSources = [],
						vars = [],
						namedImports = [],
github lttb / postjss / src / babel / index.js View on Github external
import template from 'babel-template'

import prepareConfig from '~/common/prepare-config-sync'
import getUniqHash from '~/common/utils/get-uniq-hash'

import Logger from './utils/logger'
import requireModule from './utils/require-module'
import getIndentNumber from './utils/get-indent-number'

import initPropsParser from './init-props-parser'


const argsName = getUniqHash()
const parseProps = initPropsParser(argsName)

const functionTemplate = template(`(function (${argsName} = {}) {
  ${argsName} = Object.assign(defaults, ${argsName});

  return styles;
});`)


export default ({ types: t }) => {
  let config
  let processCSSModule
  let requireCSSModule

  return {
    pre() {
      if (config) {
        return
      }
github jamietre / babel-plugin-transform-es2015-modules-commonjs-simple / src / index.js View on Github external
import { basename, extname } from "path";
import template from "babel-template";
import * as t from "babel-types";

let buildRequire = template(`
  require($0);
`);

let buildExportsModuleDeclaration = template(`
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
`);

let buildExportsFrom = template(`
  Object.defineProperty(exports, $0, {
    enumerable: true,
    get: function () {
      return $1;
    }
  });
`);

let buildLooseExportsModuleDeclaration = template(`
  exports.__esModule = true;
`);

let buildExportsAssignment = template(`
  exports.$0 = $1;
`);
github foxbenjaminfox / babel-plugin-overload / src / index.js View on Github external
function invokedTemplate(op) {
  return template(`
      (function (LEFT_ARG, RIGHT_ARG) { 
        if (LEFT_ARG !== null && LEFT_ARG !== undefined
             && LEFT_ARG[Symbol.for("${op}")])
            return LEFT_ARG[Symbol.for("${op}")](RIGHT_ARG)
        else return LEFT_ARG ${op} RIGHT_ARG
      })
  `)
}
export default function({ types: t }) {
github babel / babel / packages / babel-plugin-transform-es2015-parameters / src / default.js View on Github external
import template from "babel-template";
import * as t from "babel-types";

let buildDefaultParam = template(`
  let VARIABLE_NAME =
    ARGUMENTS.length <= ARGUMENT_KEY || ARGUMENTS[ARGUMENT_KEY] === undefined ?
      DEFAULT_VALUE
    :
      ARGUMENTS[ARGUMENT_KEY];
`);

let buildDefaultParamAssign = template(`
  if (VARIABLE_NAME === undefined) VARIABLE_NAME = DEFAULT_VALUE;
`);

let buildCutOff = template(`
  let $0 = $1[$2];
`);

function hasDefaults(node) {
  for (let param of node.params) {
    if (!t.isIdentifier(param)) return true;
  }
  return false;
}

let iifeVisitor = {
  ReferencedIdentifier(path, state) {
    let name = path.node.name;
    if (name === "eval" || (path.scope.hasOwnBinding(name) && path.scope.getOwnBinding(name).kind !== "param")) {
      state.iife = true;
      path.stop();
github ctrlplusb / code-split-component / src / plugins / babel.js View on Github external
A "modules" prop must be provided, and must contain an object literal that has a minimum of one property. Each property should be assigned a "require" statement which has a string literal within.

For example:

  
    { ({ Foo }) => Foo &&  }
  `;

function err(error) {
  throw new Error(`\n
ERROR IN code-split-component BABEL PLUGIN TRANSPILATION ATTEMPT
----------------------------------------------------------------
${error}\n`);
}

const modulesTemplate = template(`resolvedModules => require.ensure(
  [],
  require => resolvedModules(REQUIRES),
  CHUNKNAME
)`);

function getProp(props, propName) {
  return props.find(prop => prop.name.name === propName);
}

function validateProps(chunkName, modules) {
  const isValidModuleProperty = element =>
    element.type === 'ObjectProperty'
      && element.value.type === 'CallExpression'
      && element.value.callee.name === 'require'
      && element.value.arguments.length > 0
      && element.value.arguments[0].type === 'StringLiteral';

babel-template

Generate an AST from a string template.

MIT
Latest version published 6 years ago

Package Health Score

82 / 100
Full package analysis

Popular babel-template functions