How to use the @babel/core.transformFromAstSync function in @babel/core

To help you get started, we’ve selected a few @babel/core 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 appcelerator / alloy / Alloy / commands / compile / sourceMapper.js View on Github external
U.dieWithCodeFrame(`Error parsing code in ${filename}. ${e.message}`, e.loc, genMap.code);
	}

	// create source map and generated code
	var options = _.extend(_.clone(exports.OPTIONS_OUTPUT), {
		plugins: [
			[require('./ast/builtins-plugin'), compileConfig],
			[require('./ast/optimizer-plugin'), compileConfig.alloyConfig]
		]
	});
	if (compileConfig.sourcemap) {
		// Tell babel to retain the lines so they stay correct (columns go wacky, but OH WELL)
		// we produce our own source maps and we want the lines to stay as we mapped them
		options.retainLines = true;
	}
	var outputResult = babel.transformFromAstSync(ast, genMap.code, options);

	// produce the source map and embed the original source (so the template source can be passed along)
	const sourceMap = mapper.toJSON();
	sourceMap.sourcesContent = [ target.templateContent, data[markers[0]].fileContent ];

	// append pointer to the source map to the generated code
	outputResult.code += `\n//# sourceMappingURL=file://${compileConfig.dir.project}/${CONST.DIR.MAP}/${relativeOutfile}.${CONST.FILE_EXT.MAP}`;

	// write the generated controller code
	fs.mkdirpSync(path.dirname(outfile));
	chmodr.sync(path.dirname(outfile), 0755);
	fs.writeFileSync(outfile, outputResult.code.toString());
	logger.info('  created:    "' + relativeOutfile + '"');

	// write source map for the generated file
	if (compileConfig.sourcemap !== false) {
github facebook / metro / packages / metro / src / JSTransformer / worker.js View on Github external
if (options.experimentalImportSupport) {
      plugins.push([importExportPlugin, opts]);
    }

    if (options.inlineRequires) {
      plugins.push([inlineRequiresPlugin, opts]);
    }

    if (!options.dev) {
      plugins.push([constantFoldingPlugin, opts]);
    }

    plugins.push([inlinePlugin, opts]);

    ({ast} = transformFromAstSync(ast, '', {
      ast: true,
      babelrc: false,
      code: false,
      configFile: false,
      comments: false,
      compact: false,
      filename,
      plugins,
      sourceMaps: false,
    }));

    let dependencyMapName = '';
    let dependencies;
    let wrappedAst;

    // If the module to transform is a script (meaning that is not part of the
github caiyongmin / awesome-coding-javascript / src / bundler / webpack / minipack.js View on Github external
function readModule(filename) {
  // 读取文件内容
  const content = fs.readFileSync(filename, 'utf-8');
  // 解析得到文件的 AST,方便后面获得文件的依赖数组
  const ast = babylon.parse(content, {
    sourceType: 'module',
  });
  // 遍历文件 AST,获得文件依赖数组
  const dependencies = [];
  traverse(ast, {
    ImportDeclaration: ({ node }) => {
      dependencies.push(node.source.value);
    }
  });
  // 根据文件 AST 转化得到 babel 编译后的代码,options 中配置了 '@babel/preset-env' presets
  const { code } = babel.transformFromAstSync(ast, null, {
    presets: ['@babel/preset-env'],
  });

  return {
    id: ID++,
    filename,
    dependencies,
    code,
  };
}
github uber / react-view / src / ui / compiler.tsx View on Github external
const evalCode = (
  ast: babel.types.Node,
  scope: any,
  presets?: PluginItem[]
) => {
  const transformedCode = transformFromAstSync(
    ast as babel.types.Node,
    undefined,
    {
      presets: presets ? [presetReact, ...presets] : [presetReact],
      inputSourceMap: false as any,
      sourceMaps: false,
      // TS preset needs this and it doesn't seem to matter when TS preset
      // is not used, so let's keep it here?
      filename: 'file.tsx',
    }
  );
  const resultCode = transformedCode ? transformedCode.code : '';
  const scopeKeys = Object.keys(scope);
  const scopeValues = Object.values(scope);
  //@ts-ignore
  const res = new Function('React', ...scopeKeys, `return ${resultCode}`);
github facebook / flipper / static / transforms / __tests__ / flipper-requires.node.js View on Github external
test('transform react-dom requires to global object', () => {
  const src = 'require("react-dom")';
  const ast = parse(src);
  const transformed = transformFromAstSync(ast, src, babelOptions).ast;
  const {code} = generate(transformed);
  expect(code).toBe('global.ReactDOM;');
});
github facebook / flipper / static / transforms / __tests__ / flipper-requires.node.js View on Github external
test('transform react requires to global object', () => {
  const src = 'require("react")';
  const ast = parse(src);
  const transformed = transformFromAstSync(ast, src, babelOptions).ast;
  const {code} = generate(transformed);
  expect(code).toBe('global.React;');
});
github meteor / babel / index.js View on Github external
function transform(presets) {
    optionsCopy.plugins = [{
      parserOverride: parse
    }];

    optionsCopy.presets = presets;
    optionsCopy.sourceMaps = true;
    if (result.map) {
      optionsCopy.inputSourceMap = result.map;
    }

    if (result.ast) {
      result = babelCore.transformFromAstSync(
        result.ast,
        result.code,
        optionsCopy
      );
    } else {
      result = babelCore.transformSync(result.code, optionsCopy);
    }

    if (ast === false) {
      delete result.ast;
    }
  }
github uber / baseweb / documentation-site / components / yard / compiler.tsx View on Github external
const evalCode = (ast: babel.types.Node, scope: any) => {
  const transformedCode = transformFromAstSync(
    ast as babel.types.Node,
    undefined,
    {
      presets: [presetReact],
    },
  );
  const resultCode = transformedCode ? transformedCode.code : '';
  const scopeKeys = Object.keys(scope);
  const scopeValues = Object.values(scope);
  //@ts-ignore
  const res = new Function('React', ...scopeKeys, `return ${resultCode}`);
  return res(React, ...scopeValues);
};