How to use @babel/core - 10 common examples

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 ttag-org / babel-plugin-ttag / tests / functional / test_sorted_entries_without_reference_line_num.js View on Github external
it('should sort message identifiers and file location comments', () => {
        const inputFile = 'tests/fixtures/sort_by_msgid_input.js';
        const inputFile2 = 'tests/fixtures/sort_by_msgid_input2.js';
        const expectedPath = 'tests/fixtures/expected_sort_by_msgid_withou_reference_line_num.pot';
        // here we use reverse order of files, expected that references will be sorted
        babel.transformFileSync(path.join(process.cwd(), inputFile2), options);
        babel.transformFileSync(path.join(process.cwd(), inputFile), options);
        const result = fs.readFileSync(output).toString();
        const expected = fs.readFileSync(expectedPath).toString();
        expect(result).to.eql(expected);
    });
});
github decaffeinate / decaffeinate / test / support / validate.ts View on Github external
function runValidation(source: string, expectedOutput: {}, options: Options, skipNodeCheck: boolean): void {
  const compile = options.useCS2 ? cs2Compile : cs1Compile;
  const coffeeES5 = compile(source, { bare: true }) as string;
  const decaffeinateES6 = convert(source, options).code;
  const transformed = babel.transformSync(decaffeinateES6, {
    presets: ['@babel/preset-env']
  });
  const decaffeinateES5 = (transformed && transformed.code) || '';

  const coffeeOutput = runCodeAndExtract(coffeeES5);
  const decaffeinateOutput = runCodeAndExtract(decaffeinateES5);
  try {
    assertDeepEqual(decaffeinateOutput, coffeeOutput, 'decaffeinate and coffee output were different.');
  } catch (err) {
    // add some additional context for debugging
    err.message = `Additional Debug:
SOURCE
${source}
********************
INPUT -> COFFEE-SCRIPT -> ES5
${coffeeES5}
github grubersjoe / reflow / src / cli / runner.ts View on Github external
inputFiles.forEach(inputFile => {
      // Skip all invalid sources (files that match the include glob pattern, but are not JS)
      if (!isValidSource(inputFile)) {
        return;
      }

      console.log(`Transpiling ${inputFile}...`);

      try {
        const out = transformFileSync(inputFile, babelOptions);

        if (out === null || !out.code) {
          logError(`Unable to transpile ${inputFile}`, 4);
        } else {
          const outputFile = process.env.DEBUG
            ? inputFile
            : inputFile.replace(extname(inputFile), FileTypes.get(inputFile) || '.ts');

          const originalCode = String(readFileSync(inputFile));
          const output = formatOutputCode(out.code, originalCode, pluginOptions);

          if (output instanceof Error) {
            logError(`${inputFile} could not be formatted. Skipping.`, 4);
            logError(output.message, 4);
            return;
          }
github Zerthox / BetterDiscord-Plugins / scripts / build.js View on Github external
function compile() {
		try {
			const time = process.hrtime();

			// load plugin config
			const info = JSON.parse(fs.readFileSync(cfg, "utf8"));

			// generate source link
			info.source = "https://github.com/Zerthox/BetterDiscord-Plugins";

			// transform file
			const transformed = babel.transformFileSync(
				file, 
				{
					plugins: [
						["./lib/sass-importer", {
							plugin: info
						}]
					]
				}
			).code;

			// write to output file
			fs.writeFileSync(out, generateMeta(info) + generatePlugin(info, transformed));

			// console output
			console.log(chalk.green(`Compiled "${info.name}.plugin.js" to the BetterDiscord plugins folder [${Math.round(process.hrtime(time)[1] / 1000000)}ms]`));
		}
github babel / babel / packages / babel-plugin-transform-member-expression-literals / src / index.js View on Github external
exit({ node }) {
          const prop = node.property;
          if (
            !node.computed &&
            t.isIdentifier(prop) &&
            !t.isValidES3Identifier(prop.name)
          ) {
            // foo.default -> foo["default"]
            node.property = t.stringLiteral(prop.name);
            node.computed = true;
          }
        },
      },
github mattdesl / canvas-sketch-cli / src / walk-local-deps.js View on Github external
// mark this file as checked
    checked.push(file);

    const ext = (path.extname(file) || '').toLowerCase();
    if (!extensions.includes(ext)) {
      return;
    }

    if (typeof src === 'undefined') {
      src = await readFile(file, 'utf-8');
    }

    const basedir = path.dirname(file);
    let deps;
    try {
      const babelResult = babel.transform(src, {
        ast: true,
        babelrc: true,
        plugins: [
          pluginSyntaxRestSpread,
          pluginSyntaxGenerator,
          pluginDynamicImport,
          pluginCJS
        ],
        filename: file,
        sourceFileName: file,
        highlightCode: true
      });
      const result = konan(babelResult.ast);
      deps = result.strings;
    } catch (err) {
      throw err;
github babel / babel / packages / babel-plugin-transform-modules-systemjs / src / index.js View on Github external
);
              }
            }

            if (specifiers.exports.length) {
              const exportNames = [];
              const exportValues = [];
              let hasExportStar = false;

              for (const node of specifiers.exports) {
                if (t.isExportAllDeclaration(node)) {
                  hasExportStar = true;
                } else if (t.isExportSpecifier(node)) {
                  exportNames.push(node.exported.name);
                  exportValues.push(
                    t.memberExpression(t.identifier(target), node.local),
                  );
                } else {
                  // todo
                }
              }

              setterBody = setterBody.concat(
                constructExportCall(
                  path,
                  t.identifier(exportIdent),
                  exportNames,
                  exportValues,
                  hasExportStar ? t.identifier(target) : null,
                ),
              );
            }
github babel / babel / packages / babel-plugin-transform-block-scoping / src / index.js View on Github external
if (state.ignoreLabeless) return;

        // break statements mean something different in this context
        if (t.isBreakStatement(node) && state.inSwitchCase) return;
      }

      state.hasBreakContinue = true;
      state.map[loopText] = node;
      replace = t.stringLiteral(loopText);
    }

    if (path.isReturnStatement()) {
      state.hasReturn = true;
      replace = t.objectExpression([
        t.objectProperty(
          t.identifier("v"),
          node.argument || scope.buildUndefinedNode(),
        ),
      ]);
    }

    if (replace) {
      replace = t.returnStatement(replace);
      replace[this.LOOP_IGNORE] = true;
      path.skip();
      path.replaceWith(t.inherits(replace, node));
    }
  },
};
github milesj / babel-plugin-typescript-to-proptypes / src / convertBabelToPropTypes.ts View on Github external
// element
    } else if (
      isReactTypeMatch(name, 'Element', 'JSX') ||
      isReactTypeMatch(name, 'ReactElement', reactImportedName) ||
      isReactTypeMatch(name, 'ComponentElement', reactImportedName) ||
      isReactTypeMatch(name, 'FunctionComponentElement', reactImportedName) ||
      isReactTypeMatch(name, 'DOMElement', reactImportedName) ||
      isReactTypeMatch(name, 'SFCElement', reactImportedName)
    ) {
      return createMember(t.identifier('element'), propTypesImportedName);

      // oneOfType
    } else if (isReactTypeMatch(name, 'Ref', reactImportedName)) {
      return createCall(
        t.identifier('oneOfType'),
        [
          t.arrayExpression([
            createMember(t.identifier('string'), propTypesImportedName),
            createMember(t.identifier('func'), propTypesImportedName),
            createMember(t.identifier('object'), propTypesImportedName),
          ]),
        ],
        propTypesImportedName,
      );

      // function
    } else if (name.endsWith('Handler')) {
      return createMember(t.identifier('func'), propTypesImportedName);

      // object
    } else if (name.endsWith('Event')) {
github vfeskov / vanilla-back-to-top / npm-scripts / build.js View on Github external
async function makeBackwardsCompatible (source) {
  const cssProcessed = await processCss(source)
  return babel.transformSync(cssProcessed, {
    presets: [[presetEnv, {
      // use browserslist config from package.json
      useBuiltIns: 'entry'
    }]]
  }).code
}