@babel/core#TransformOptions TypeScript Examples

The following examples show how to use @babel/core#TransformOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
getBabelConfig = (input?: BabelConfigOptions): TransformOptions => {
    const options = fillBabelConfigOptions(input);
    const {mode, hot, hostType, cwd, srcDirectory} = options;
    const transform = getTransformBabelConfig(options);
    const requireReactOptimization = mode === 'production' && hostType === 'application';
    const plugins: Array<PluginItem | false> = [
        // 这东西必须放在最前面,不然其它插件会转义出如`function Wrapper()`这样的函数,这个插件再插入代码就会出问题
        requireFileName(options) && [
            debugReactComponentFileName,
            {
                srcDirectory: path.resolve(cwd, srcDirectory),
                fullPathPrefix: options.openInEditorPrefix,
            },
        ],
        ...transform.plugins || [],
        requireReactOptimization && pluginRemovePropTypes,
        hot && [pluginReactRefresh, {skipEnvCheck: true}],
    ];

    return {presets: transform.presets, plugins: compact(plugins)};
}
Example #2
Source File: babel-plugin.test.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
babelOptions: TransformOptions = {
  babelrc: false,
  configFile: false,
  compact: false,
  parserOpts: {
    sourceType: 'module',
    plugins: [
      'typescript',
      'jsx',
    ],
  },
}
Example #3
Source File: babelTransform.ts    From web with MIT License 6 votes vote down vote up
systemJsConfig: TransformOptions = {
  ...es5Config,
  plugins: [
    ...(es5Config.plugins ?? []),
    require.resolve('@babel/plugin-proposal-dynamic-import'),
    require.resolve('@babel/plugin-transform-modules-systemjs'),
    // systemjs adds template literals, we do systemjs after (potential)
    // es5 compilation so we need to ensure it stays es5
    require.resolve('@babel/plugin-transform-template-literals'),
  ],
}
Example #4
Source File: babelTransform.ts    From web with MIT License 6 votes vote down vote up
es5Config: TransformOptions = {
  caller: {
    name: '@web/dev-server-legacy',
    supportsStaticESM: true,
  },
  sourceType: 'module',
  babelrc: false,
  configFile: false,
  presets: [
    [
      require.resolve('@babel/preset-env'),
      {
        targets: ['defaults', 'ie 10'],
        useBuiltIns: false,
        shippedProposals: true,
        modules: false,
        bugfixes: true,
      },
    ],
  ],
  /**
   * Enable syntax plugins for stage 3 features. This does **not** transform them,
   * it only ensures that babel does not crash when you're using them.
   */
  plugins: [
    require.resolve('@babel/plugin-syntax-import-meta'),
    require.resolve('@babel/plugin-syntax-class-properties'),
    require.resolve('@babel/plugin-syntax-numeric-separator'),
    require.resolve('@babel/plugin-syntax-dynamic-import'),
  ],
}
Example #5
Source File: babelTransform.ts    From web with MIT License 6 votes vote down vote up
export async function babelTransform(filename: string, source: string, config: TransformOptions) {
  const largeFile = source.length > 100000;
  const result = await transformAsync(source, {
    filename,
    // prevent generating pretty output for large files
    compact: largeFile,
    // babel runs out of memory when processing source maps andfor large files
    sourceMaps: !largeFile,
    ...config,
  });
  if (!result || typeof result.code !== 'string') {
    throw new Error('Failed to transform');
  }
  return result.code;
}
Example #6
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
transformFile = async (file: string, baseIn: string, baseOut: string, options: TransformOptions) => {
    // 定义文件不处理
    if (file.endsWith('.d.ts')) {
        return;
    }

    const result = await transformFileAsync(file, options);

    if (!result || result.code == null || result.map == null) {
        logger.error(`Failed to transform ${file}`);
        process.exit(20);
    }

    const relative = path.relative(baseIn, file);
    const destination = path.join(baseOut, changeExtension(relative, '.js'));
    const writingFiles = [
        writeFile(destination, result.code + `\n//# sourceMappingURL=${destination}.map`),
        writeFile(`${destination}.map`, JSON.stringify(result.map)),
    ];
    await Promise.all(writingFiles);
}
Example #7
Source File: index.test.ts    From reskript with MIT License 5 votes vote down vote up
pluginLengthDifference = (from: TransformOptions, to: TransformOptions) => {
    return (to.plugins?.length ?? 0) - (from.plugins?.length ?? 0);
}
Example #8
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
getParseOnlyBabelConfig = (options?: BabelConfigOptions): TransformOptions => {
    return getParseOnlyBabelConfigFilled(fillBabelConfigOptions(options));
}
Example #9
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
getTransformBabelConfig = (input?: BabelConfigOptions): TransformOptions => {
    return getTransformBabelConfigFilled(fillBabelConfigOptions(input));
}
Example #10
Source File: index.d.ts    From amazon-kinesis-video-streams-webrtc-sdk-js-with-amazon-cognito with MIT No Attribution 5 votes vote down vote up
transformer: BabelJestTransformer & {
    createTransformer: (options?: TransformOptions) => BabelJestTransformer;
}
Example #11
Source File: internal.ts    From reskript with MIT License 5 votes vote down vote up
getParseOnlyBabelConfig = (options?: BabelConfigOptions): TransformOptions => {
    return getParseOnlyBabelConfigFilled(fillBabelConfigOptions(options));
}
Example #12
Source File: internal.ts    From reskript with MIT License 5 votes vote down vote up
getTransformBabelConfig = (input?: BabelConfigOptions): TransformOptions => {
    return getTransformBabelConfigFilled(fillBabelConfigOptions(input));
}
Example #13
Source File: finalize.test.ts    From reskript with MIT License 5 votes vote down vote up
describe('finalize', () => {
    test('can receive a fully resolved webpack config and modify it', async () => {
        const finalize = vi.fn((config: FinalizableWebpackConfiguration) => ({...config, mode: 'production' as const}));
        const options = {...BUILD_CMD, cwd: currentDirectory};
        const projectSettings = await readProjectSettings(options) as WebpackProjectSettings;
        const withFinalize = {
            ...projectSettings,
            build: {
                ...projectSettings.build,
                finalize,
            },
        };
        const context: BuildContext = {
            cwd: currentDirectory,
            mode: 'development',
            usage: 'build',
            srcDirectory: 'src',
            hostPackageName: 'test',
            buildVersion: '000000',
            buildTime: (new Date()).toISOString(),
            features: {},
            buildTarget: 'stable',
            isDefaultTarget: false,
            entries: [],
            projectSettings: withFinalize,
        };
        const config = await createWebpackConfig(context);
        expect(finalize).toHaveBeenCalled();
        expect(typeof finalize.mock.calls[0][0]).toBe('object');
        expect(typeof finalize.mock.calls[0][0].module).toBe('object');
        expect(config.mode).toBe('production');
    });

    test('can modify babel config', async () => {
        const finalize = vi.fn((config: TransformOptions) => ({...config, comments: false}));
        const options = {...BUILD_CMD, cwd: currentDirectory};
        const projectSettings = await readProjectSettings(options) as WebpackProjectSettings;
        const withFinalize = {
            ...projectSettings,
            build: {
                ...projectSettings.build,
                script: {
                    ...projectSettings.build.script,
                    finalize,
                },
            },
        };
        const context: BuildContext = {
            cwd: currentDirectory,
            mode: 'development',
            usage: 'build',
            srcDirectory: 'src',
            hostPackageName: 'test',
            buildVersion: '000000',
            buildTime: (new Date()).toISOString(),
            features: {},
            buildTarget: 'stable',
            isDefaultTarget: false,
            entries: [],
            projectSettings: withFinalize,
        };
        await createWebpackConfig(context);
        expect(finalize).toHaveBeenCalled();
        expect(typeof finalize.mock.calls[0][0]).toBe('object');
        expect(typeof finalize.mock.calls[0][0].presets).toBe('object');
    });
});
Example #14
Source File: transform.ts    From design-systems-cli with MIT License 5 votes vote down vote up
options: TransformOptions = {
  caller: {
    name: '@design-systems/cli-jest',
    supportsStaticESM: false
  },
  compact: false,
  sourceMaps: 'both'
}
Example #15
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
run = async (cmd: BabelCommandLineArgs, file: string): Promise<void> => {
    if (!file) {
        return;
    }

    const {outDirectory, clean, copy, mode, polyfill, uses} = cmd;

    if (outDirectory) {
        if (clean) {
            await fs.rm(outDirectory, {recursive: true, force: true});
        }

        await fs.mkdir(outDirectory, {recursive: true});
    }

    const babelConfigOptions: BabelConfigOptions = {
        mode,
        polyfill,
        uses,
        hot: false,
        hostType: 'application',
        modules: false,
    };
    const babelConfig: TransformOptions = {
        ...getTransformBabelConfig(babelConfigOptions),
        sourceMaps: !!outDirectory,
        babelrc: false,
    };
    const stat = await fs.stat(file);

    if (stat.isFile()) {
        if (outDirectory) {
            await transformFile(file, path.dirname(file), outDirectory, babelConfig);
        }
        else {
            const result = await transformFileAsync(file, babelConfig);
            printInConsole(result?.code);
        }
    }
    else {
        if (!outDirectory) {
            logger.error('Cannot output to terminal with directory input, specify a single file or use --out-dir.');
            process.exit(21);
        }

        await transformDirectory(file, outDirectory, babelConfig);

        if (copy) {
            const files = await globby(['**', '!**/*.{ts,js,tsx,jsx}'], {cwd: file, absolute: true});
            const limit = pLimit(2);
            await Promise.all(files.map(v => limit(copyFile, v, file, outDirectory)));
        }
    }
}
Example #16
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
transformDirectory = async (dir: string, out: string, options: TransformOptions) => {
    const files = await globby('**/*.{js,jsx,ts,tsx}', {cwd: dir, absolute: true});
    await Promise.all(files.map(f => transformFile(f, dir, out, options)));
}
Example #17
Source File: index.d.ts    From amazon-kinesis-video-streams-webrtc-sdk-js-with-amazon-cognito with MIT No Attribution 5 votes vote down vote up
transformer: BabelJestTransformer & {
    createTransformer: (options?: TransformOptions) => BabelJestTransformer;
}