esbuild#transform TypeScript Examples

The following examples show how to use esbuild#transform. 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: transform.ts    From vite-plugin-mdx with MIT License 6 votes vote down vote up
export function createTransformer(
  root: string,
  namedImports = inferNamedImports(root)
) {
  const mdx = requireMdx(root)
  const imports = Object.entries(namedImports).map(
    ([packageName, imported]) => {
      assertImportExists(packageName, root)
      return Array.isArray(imported)
        ? `import { ${imported.join(', ')} } from '${packageName}'`
        : `import ${imported} from '${packageName}'`
    }
  )

  return async function transform(code_mdx: string, mdxOptions?: MdxOptions) {
    const code_jsx = await mdx(code_mdx, mdxOptions as any)
    const code_es2019 = await jsxToES2019(code_jsx)
    return imports.concat('', code_es2019).join('\n')
  }
}
Example #2
Source File: transform.ts    From vite-plugin-mdx with MIT License 6 votes vote down vote up
async function jsxToES2019(code_jsx: string) {
  // We use `esbuild` ourselves instead of letting Vite doing the esbuild transform,
  // because there don't seem to be a way to change the esbuild options for specific
  // files only: https://vitejs.dev/config/#esbuild

  /* Uncomment this to inspect the type `TransformOptions`
  type TransformOptions = Pick<Parameters<typeof esBuild.transform>, 1>[1];
  let t: TransformOptions;
  t!.format
  t!.jsxFactory
  //*/

  let { code: code_es2019 } = await transform(code_jsx, {
    loader: 'jsx',
    jsxFactory: 'mdx',
    target: 'es2019'
  })

  // TODO stabilize this bugfix
  code_es2019 = code_es2019.replace(
    'export default function MDXContent',
    'export default MDXContent; function MDXContent'
  )

  return code_es2019
}
Example #3
Source File: EsbuildPlugin.ts    From web with MIT License 6 votes vote down vote up
async transform(context: Context) {
    let loader: Loader;

    if (context.response.is('html')) {
      // we are transforming inline scripts
      loader = 'js';
    } else {
      const fileExtension = path.posix.extname(context.path);
      loader = this.esbuildConfig.loaders[fileExtension];
    }

    if (!loader) {
      // we are not handling this file
      return;
    }

    const target = getEsbuildTarget(this.esbuildConfig.target, context.headers['user-agent']);
    if (target === 'esnext' && loader === 'js') {
      // no need run esbuild, this happens when compile target is set to auto and the user is on a modern browser
      return;
    }

    const filePath = getRequestFilePath(context.url, this.config!.rootDir);
    if (context.response.is('html')) {
      this.transformedHtmlFiles.push(context.path);
      return this.__transformHtml(context, filePath, loader, target);
    }

    return this.__transformCode(context.body as string, filePath, loader, target);
  }
Example #4
Source File: EsbuildPlugin.ts    From web with MIT License 5 votes vote down vote up
private async __transformCode(
    code: string,
    filePath: string,
    loader: Loader,
    target: string | string[],
  ): Promise<string> {
    try {
      const transformOptions: TransformOptions = {
        sourcefile: filePath,
        sourcemap: 'inline',
        loader,
        target,
        // don't set any format for JS-like formats, otherwise esbuild reformats the code unnecessarily
        format: ['js', 'jsx', 'ts', 'tsx'].includes(loader) ? undefined : 'esm',
        jsxFactory: this.esbuildConfig.jsxFactory,
        jsxFragment: this.esbuildConfig.jsxFragment,
        define: this.esbuildConfig.define,
        tsconfigRaw: this.tsconfigRaw,
      };

      const { code: transformedCode, warnings } = await transform(code, transformOptions);

      if (warnings) {
        const relativePath = path.relative(process.cwd(), filePath);

        for (const warning of warnings) {
          if (!filteredWarnings.some(w => warning.text.includes(w))) {
            this.logger!.warn(
              `[@web/test-runner-esbuild] Warning while transforming ${relativePath}: ${warning.text}`,
            );
          }
        }
      }

      return transformedCode;
    } catch (e) {
      if (Array.isArray(e.errors)) {
        const msg = e.errors[0] as Message;

        if (msg.location) {
          throw new PluginSyntaxError(
            msg.text,
            filePath,
            code,
            msg.location.line,
            msg.location.column,
          );
        }

        throw new Error(msg.text);
      }

      throw e;
    }
  }