How to use the @babel/template.default function in @babel/template

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 parcel-bundler / parcel / src / scope-hoisting / concat.js View on Github external
const {relative} = require('path');
const template = require('@babel/template').default;
const t = require('@babel/types');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const treeShake = require('./shake');
const mangleScope = require('./mangler');
const {getName, getIdentifier} = require('./utils');

const EXPORTS_RE = /^\$([^$]+)\$exports$/;

const DEFAULT_INTEROP_TEMPLATE = template(
  'var NAME = $parcel$interopDefault(MODULE)'
);
const THROW_TEMPLATE = template('$parcel$missingModule(MODULE)');
const REQUIRE_TEMPLATE = template('require(ID)');

module.exports = (packager, ast) => {
  let {assets} = packager;
  let replacements = new Map();
  let imports = new Map();
  let referenced = new Set();

  // Build a mapping of all imported identifiers to replace.
  for (let asset of assets.values()) {
    for (let name in asset.cacheData.imports) {
      let imp = asset.cacheData.imports[name];
      imports.set(name, [packager.resolveModule(asset.id, imp[0]), imp[1]]);
github parcel-bundler / parcel / src / scope-hoisting / concat.js View on Github external
const {relative} = require('path');
const template = require('@babel/template').default;
const t = require('@babel/types');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const treeShake = require('./shake');
const mangleScope = require('./mangler');
const {getName, getIdentifier} = require('./utils');

const EXPORTS_RE = /^\$([^$]+)\$exports$/;

const DEFAULT_INTEROP_TEMPLATE = template(
  'var NAME = $parcel$interopDefault(MODULE)'
);
const THROW_TEMPLATE = template('$parcel$missingModule(MODULE)');
const REQUIRE_TEMPLATE = template('require(ID)');

module.exports = (packager, ast) => {
  let {assets} = packager;
  let replacements = new Map();
  let imports = new Map();
  let referenced = new Set();

  // Build a mapping of all imported identifiers to replace.
  for (let asset of assets.values()) {
    for (let name in asset.cacheData.imports) {
      let imp = asset.cacheData.imports[name];
      imports.set(name, [packager.resolveModule(asset.id, imp[0]), imp[1]]);
    }
  }

  function replaceExportNode(module, originalName, path) {
github fusionjs / fusionjs / fusion-cli / build / babel-plugins / babel-plugin-experimentation / index.js View on Github external
sourceType: 'module',
  }
);

const fileChunkIdTemplate = template(`const CHUNKIDS_ID = LOCAL_ID(FILENAME);`);

// TODO(#4): There might be some issues related to npm module tree resolution here.
// How can we ensure that the fusion-experimentation instance imported here and elsewhere are the same?
const singletonImport = template(
  `
    import { nodeSingleton as LOCAL_SINGLETON } from 'fusion-experimentation';
  `,
  {sourceType: 'module'}
);

const builder = template(
  `
    LOCAL_SINGLETON.add(FILENAME, CHUNKIDS_ID, EXPERIMENTS);

    if (module.hot) {
      module.hot.dispose(() => {
        LOCAL_SINGLETON.dispose(FILENAME, CHUNKIDS_ID, EXPERIMENTS);
      });
    }

  `,
  {sourceType: 'module'}
);

/**
 * Appends a node to the program body and returns the path of the inserted node
 */
github egoist / babel-plugin-transform-vue-template / index.js View on Github external
function compilePath(t, path, template) {
  const { errors, tips, render, staticRenderFns } = compile(template)

  if (errors.length > 0) {
    errors.forEach(error => console.error(error))
  }
  if (tips.length > 0) {
    tips.forEach(tip => console.log(tip))
  }

  const renderFnValue = babelTemplate(stripWith(toFunction(render, 'render')))()
  renderFnValue.type = 'FunctionExpression'

  const staticRenderFnsValue = babelTemplate(
    stripWith(`[${staticRenderFns.map(fn => toFunction(fn)).join(',')}]`)
  )().expression

  path.parentPath.replaceWithMultiple([
    t.objectProperty(t.identifier('render'), renderFnValue),
    t.objectProperty(t.identifier('staticRenderFns'), staticRenderFnsValue)
  ])
}
github doczjs / docz / other-packages / babel-plugin-export-metadata / src / index.js View on Github external
const path = require('path')
const { default: template } = require('@babel/template')
const { get } = require('lodash')

const buildFileMeta = template(`
  if (typeof ID !== 'undefined' && ID && ID === Object(ID) && Object.isExtensible(ID) && !ID.hasOwnProperty('__filemeta')) {
    Object.defineProperty(ID, '__filemeta', {
      configurable: true,
      value: {
        name: NAME,
        filename: FILENAME
      }
    });
  }
`)

const replaceExportDefault = template(`
  import NAME from 'SOURCE'
  export default NAME
`)
github meteor / babel / plugins / dynamic-import.js View on Github external
module.exports = function () {
  var template = require("@babel/template").default;
  var buildImport = template("module.dynamicImport(SOURCE)");

  return {
    name: "transform-meteor-dynamic-import",
    inherits: require("@babel/plugin-syntax-dynamic-import").default,
    visitor: {
      CallExpression: function (path) {
        if (path.node.callee.type === "Import") {
          path.replaceWith(buildImport({
            SOURCE: path.node.arguments
          }));
        }
      }
    }
  };
};
github zhangdaren / miniprogram-to-uniapp / src / wx2uni / jsHandle.js View on Github external
}

		//占个位
		ast = buildRequire({
			METHODS: babelUtil.arrayToObject([])
		});
	} else {
		//插入setData()
		const node = babelUtil.getSetDataFunAST();
		vistors.methods.handle(node);

		//非app.js文件
		if (astType === "Behavior") {
			buildRequire = template(behaviorTemplate);
		} else if (astType === "Behavior2") {
			buildRequire = template(behaviorTemplate2);
		} else {
			buildRequire = template(componentTemplate);
		}

		//处理data下变量名与函数重名的问题,或函数名为系统关键字,如delete等
		const dataArr = vistors.data.getData();
		let dataNameList = {};
		for (const item of dataArr) {
			dataNameList[item.key.name] = true;
		}

		const methods = vistors.methods.getData();
		for (const item of methods) {
			const keyName = item.key.name;
			if (dataNameList[keyName] || utils.isReservedName(keyName)) {
				item.key.name = utils.getFunctionAlias(item.key.name);
github appcelerator / alloy / Alloy / commands / compile / ast / handle-alloy-globals.js View on Github external
const ALLOY_GLOBALS_TO_CHECK = [ 'Alloy', '_', 'Backbone' ];
const template = require('@babel/template').default;

const buildRequire = template(`
	var VARIABLE = REQUIRECALL;
`);
module.exports = function(babel) {
	return {
		name: 'app.js top level variables global transform',
		visitor: {
			CallExpression: function (path, state) {
				const node = path.node;
				if (node.callee.name !== 'require') {
					return;
				}
				if (!node.arguments || !node.arguments[0]) {
					return;
				}
				checkStatement(node.arguments[0].value, state);
			},
github Marwan01 / food-converter / node_modules / metro / src / JSTransformer / worker / import-export-plugin.js View on Github external
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++)
      arr2[i] = arr[i];
    return arr2;
  }
}

const template = require("@babel/template").default;

/**
 * Produces a Babel template that transforms an "import * as x from ..." or an
 * "import x from ..." call into a "const x = importAll(...)" call with the
 * corresponding id in it.
 */
const importTemplate = template(`
  var LOCAL = IMPORT(FILE);
`);
/**
 * Produces a Babel template that transforms an "import {x as y} from ..." into
 * "const y = require(...).x" call with the corresponding id in it.
 */

const importNamedTemplate = template(`
  var LOCAL = require(FILE).REMOTE;
`);
/**
 * Produces a Babel template that transforms an "import ..." into
 * "require(...)", which is considered a side-effect call.
 */

const importSideEffect = template(`
github Jam3 / babel-plugin-static-fs / lib / fs.js View on Github external
var fs = require('fs');
var t = require('@babel/types');
var template = require('@babel/template').default;

var buffer = template('Buffer(CONTENT, ENC)');

module.exports = function (instance) {
  return {
    readFile: notSupported('readFile'),
    readdir: notSupported('readdir'),

    readdirSync: function (file) {
      var list = fs.readdirSync(file);
      return t.valueToNode(list);
    },

    readFileSync: function (file, enc) {
      var isBuffer = false;
      if (enc === null || enc === undefined) {
        isBuffer = true;
        enc = 'base64';