esbuild#BuildResult TypeScript Examples

The following examples show how to use esbuild#BuildResult. 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: esbuild.ts    From magic-js with MIT License 6 votes vote down vote up
/**
 * Returns a function that can be used to handle rebuild events from ESBuild.
 */
function onRebuildFactory(options: ESBuildOptions) {
  return async (error: BuildFailure | null, result: BuildResult | null) => {
    if (error) {
      console.error(error.message);
    } else {
      await printOutputSizeInfo(options);
    }
  };
}
Example #2
Source File: verify-code.ts    From solita with Apache License 2.0 6 votes vote down vote up
export async function analyzeCode(ts: string) {
  const hash = createHash(Buffer.from(ts))
  const filename = `${hash}.ts`
  const filePath = path.join(tmpdir, filename)
  await fs.writeFile(filePath, ts, 'utf8')

  const outfilePath = `${filePath}.js`
  const buildResult: BuildResult = await build({
    absWorkingDir: tmpdir,
    entryPoints: [filePath],
    outfile: outfilePath,
  })
  const js = await fs.readFile(outfilePath, 'utf8')
  return {
    js,
    ts,
    errors: buildResult.errors,
    warnings: buildResult.warnings,
  }
}
Example #3
Source File: esbuildBundler.ts    From elderjs with MIT License 4 votes vote down vote up
svelteHandler = async ({ elderConfig, svelteConfig, replacements, restartHelper }) => {
  try {
    const builders: { ssr?: BuildResult; client?: BuildResult } = {};

    // eslint-disable-next-line global-require
    const pkg = require(path.resolve(elderConfig.rootDir, './package.json'));
    const globPath = path.resolve(elderConfig.rootDir, `./src/**/*.svelte`);
    const initialEntryPoints = glob.sync(globPath);
    const sveltePackages = getPackagesWithSvelte(pkg, elderConfig);
    const elderPlugins = getPluginLocations(elderConfig);

    builders.ssr = await build({
      entryPoints: [...initialEntryPoints, ...elderPlugins.files],
      bundle: true,
      outdir: elderConfig.$$internal.ssrComponents,
      plugins: [
        esbuildPluginSvelte({
          type: 'ssr',
          sveltePackages,
          elderConfig,
          svelteConfig,
        }),
      ],
      watch: {
        onRebuild(error) {
          restartHelper('ssr');
          if (error) console.error('ssr watch build failed:', error);
        },
      },
      format: 'cjs',
      target: ['node12'],
      platform: 'node',
      sourcemap: !production,
      minify: production,
      outbase: 'src',
      external: pkg.dependents ? [...Object.keys(pkg.dependents)] : [],
      define: {
        'process.env.componentType': "'server'",
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        ...replacements,
      },
    });

    builders.client = await build({
      entryPoints: [...initialEntryPoints.filter((i) => i.includes('src/components')), ...elderPlugins.files],
      bundle: true,
      outdir: elderConfig.$$internal.clientComponents,
      entryNames: '[dir]/[name].[hash]',
      plugins: [
        esbuildPluginSvelte({
          type: 'client',
          sveltePackages,
          elderConfig,
          svelteConfig,
        }),
      ],
      watch: {
        onRebuild(error) {
          if (error) console.error('client watch build failed:', error);
          restartHelper('client');
        },
      },
      format: 'esm',
      target: ['es2020'],
      platform: 'browser',
      sourcemap: !production,
      minify: true,
      splitting: true,
      chunkNames: 'chunks/[name].[hash]',
      logLevel: 'error',
      outbase: 'src',
      define: {
        'process.env.componentType': "'browser'",
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        ...replacements,
      },
    });

    restartHelper('start');

    const restart = async () => {
      if (builders.ssr) await builders.ssr.stop();
      if (builders.client) await builders.client.stop();
      restartHelper('reset');
      return svelteHandler({
        elderConfig,
        svelteConfig,
        replacements,
        restartHelper,
      });
    };

    return restart;
  } catch (e) {
    console.error(e);
  }
}
Example #4
Source File: cli.ts    From nota with MIT License 4 votes vote down vote up
cli = (
  externalOptions?: CliOptions
): ((extra: BuildOptions) => Promise<[BuildResult, BuildOptions]>) => {
  let options =
    externalOptions ||
    (program
      .option("-w, --watch", "Watch for changes and rebuild")
      .option("-g, --debug", "Do not minify and include source maps")
      .option("-t, --typescript", "Run typescript")
      .parse(process.argv)
      .opts() as CliOptions);

  let pkg = getManifest();
  let keys = (map?: IDependencyMap) => Object.keys(map || {});
  let pkgExternal = keys(pkg.dependencies).concat(keys(pkg.peerDependencies));

  return async (extra: BuildOptions = {}) => {
    let plugins = extra.plugins || [];
    let format = extra.format || "esm";

    let external = (format != "iife" ? pkgExternal : []).concat(extra.external || []);

    if (format == "esm") {
      plugins.push(esmExternalsPlugin({ externals: external }));
    }

    let loader: { [ext: string]: Loader } = {
      ".otf": "file",
      ".woff": "file",
      ".woff2": "file",
      ".ttf": "file",
      ".wasm": "file",
      ".bib": "text",
      ".png": "file",
      ".jpg": "file",
      ".jpeg": "file",
      ".gif": "file",
      ...(extra.loader || {}),
    };

    let outpaths: BuildOptions = {};
    if (extra.outdir) {
      outpaths.outdir = extra.outdir;
    } else if (extra.outfile) {
      outpaths.outfile = extra.outfile;
    } else {
      extra.outdir = "dist";
    }

    let debug = options.debug || options.watch !== undefined;
    let watch: WatchMode | undefined =
      typeof options.watch === "object"
        ? options.watch
        : options.watch
        ? {
            onRebuild() {
              log.info("Rebuilt.");
            },
          }
        : undefined;

    let entryPoints = extra.entryPoints;
    if (!entryPoints) {
      entryPoints = [(await fileExists("./lib/index.ts")) ? "./lib/index.ts" : "./lib/index.tsx"];
    }

    if (options.ts || _.some(entryPoints, (p: string) => path.extname(p).startsWith(".ts"))) {
      plugins.push(tscPlugin());
    }

    let opts = {
      ...extra,
      ...outpaths,
      entryPoints,
      watch,
      external,
      plugins,
      format,
      loader,
      bundle: extra.bundle !== undefined ? extra.bundle : true,
      minify: extra.minify !== undefined ? extra.minify : !debug,
      sourcemap: extra.sourcemap !== undefined ? extra.sourcemap : debug,
    };

    let start = _.now();
    let result = await esbuild.build(opts);
    log.info(`Built in ${((_.now() - start) / 1000).toFixed(2)}s.`);
    return [result, opts];
  };
}