esbuild#build TypeScript Examples
The following examples show how to use
esbuild#build.
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: dev.ts From gdmod with MIT License | 6 votes |
/**
* Builds a GDMod code bundle out of the main es-module.
* @param {*} to
* @param {*} config
*/
function buildBundle(to: string, config: BuildOptions = {}) {
return build(
merge({}, config, getDefaultBuildConfiguration(), {
outfile: to,
plugins: [
globalExternals({
"@gdmod/api": {
varName: "GDAPI",
namedExports: require("../GDAPI_Signature.json"),
},
}),
],
})
);
}
Example #2
Source File: config.ts From fect with MIT License | 6 votes |
bundleConfigFile = async (filePath: string, esm = false) => {
const bundle = await build({
entryPoints: [filePath],
outfile: 'out.js',
write: false,
platform: 'node',
bundle: true,
format: esm ? 'esm' : 'cjs',
metafile: true,
plugins: [externalizeDeps]
})
// eslint-disable-next-line prefer-destructuring
const { text } = bundle.outputFiles[0]
return {
code: text,
dependencies: bundle.metafile ? Object.keys(bundle.metafile.inputs) : []
}
}
Example #3
Source File: index.test.ts From esbuild-plugin-less with Do What The F*ck You Want To Public License | 6 votes |
buildLess = async ({ lessOptions }: { lessOptions?: Less.Options } = {}) => {
const buildOptions: BuildOptions = {
entryPoints: [path.resolve(__dirname, '../', 'example', 'index.ts')],
bundle: true,
write: false,
minify: true,
outdir: path.resolve(__dirname, 'output'),
loader: {
'.ts': 'ts',
},
plugins: [lessLoader(lessOptions)],
};
const { outputFiles } = await build(buildOptions);
return outputFiles;
}
Example #4
Source File: index.test.ts From esbuild-plugin-less with Do What The F*ck You Want To Public License | 6 votes |
buildLessWithOption = async ({
lessOptions,
loaderOptions,
}: { lessOptions?: Less.Options; loaderOptions?: LoaderOptions } = {}) => {
const buildOptions: BuildOptions = {
entryPoints: [path.resolve(__dirname, '../', 'example', 'index-custom-filter.ts')],
bundle: true,
write: false,
minify: true,
outdir: path.resolve(__dirname, 'output'),
loader: {
'.ts': 'ts',
},
plugins: [lessLoader(lessOptions, loaderOptions)],
};
const { outputFiles } = await build(buildOptions);
return outputFiles;
}
Example #5
Source File: build.ts From esbuild-plugin-less with Do What The F*ck You Want To Public License | 6 votes |
build({
watch: isProduction
? false
: {
onRebuild(error) {
if (!error) {
console.log('Build succeeded');
}
},
},
entryPoints: [path.resolve(__dirname, 'index.ts')],
bundle: true,
outdir: path.resolve(__dirname, 'output'),
plugins: [
lessLoader({
globalVars: {
primaryColor: '#ff0000',
},
}),
],
loader: {
'.ts': 'ts',
},
}).catch((e) => console.error(e.message));
Example #6
Source File: build.ts From esbuild-plugin-less with Do What The F*ck You Want To Public License | 6 votes |
createBuild = () => {
formats.map((format) => {
const outputFilename = getOutputFilename(format);
build({
entryPoints: [path.resolve(__dirname, '..', 'src', 'index.ts')],
bundle: true,
minify: true,
platform: 'node',
loader: {
'.ts': 'ts',
},
external: ['less', 'path', 'fs'],
outfile: path.resolve(__dirname, '..', 'build', outputFilename),
format,
})
.then(() => {
console.info(`— ${outputFilename} was built`);
})
.catch((e) => {
console.info(`? ${outputFilename} build error:`);
console.error(e);
});
});
}
Example #7
Source File: verify-code.ts From solita with Apache License 2.0 | 6 votes |
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 #8
Source File: CliProgram.ts From joplin-utils with MIT License | 6 votes |
private async buildScripts(entryPoints: string[]) {
await build({
entryPoints: entryPoints,
bundle: true,
outdir: path.resolve(this.config.basePath, 'dist'),
platform: 'node',
sourcemap: 'external',
format: 'cjs',
})
}
Example #9
Source File: CliProgram.ts From joplin-utils with MIT License | 6 votes |
private async buildScript(entryPoint: string) {
await build({
entryPoints: [entryPoint],
bundle: true,
outdir: path.resolve(this.config.basePath, 'dist'),
platform: 'node',
sourcemap: 'external',
format: 'cjs',
})
}
Example #10
Source File: CliProgram.ts From joplin-utils with MIT License | 6 votes |
async build(isWatch: boolean): Promise<void> {
const entryPoints = await promise(
path.resolve(this.config.basePath, 'src/*.ts'),
)
await Promise.all([this.buildScripts(entryPoints), this.copyManifest()])
if (isWatch) {
await watch(['src/manifest.json', 'src/*.ts'], {
cwd: this.config.basePath,
}).on('change', async (filePath) => {
if (filePath.endsWith('manifest.json')) {
await this.copyManifest()
console.info('copy manifest.json')
} else if (filePath.endsWith('.ts')) {
await this.buildScript(path.resolve(this.config.basePath, filePath))
console.info('buildScript: ', filePath)
}
})
return
}
const pkgName = (
await readJson(path.resolve(this.config.basePath, 'package.json'))
).name
await createArchive({
sourceDir: path.resolve(this.config.basePath, 'dist'),
destPath: pkgName + '.jpl',
})
}
Example #11
Source File: optmize.ts From toy-vite with MIT License | 6 votes |
export async function optmize(opts: { pkgs: string[] }) {
const deps = opts.pkgs.reduce((memo, pkg) => {
// TODO: 优先解析包的 esm 文件
memo[pkg] = resolve.sync(pkg, {
basedir: appRoot,
});
return memo;
}, {} as Record<string, string>);
await build({
entryPoints: opts.pkgs,
bundle: true,
format: 'esm',
logLevel: 'error',
splitting: true,
sourcemap: true,
outdir: cache,
treeShaking: 'ignore-annotations',
metafile: true,
define: {
'process.env.NODE_ENV': JSON.stringify('development'),
},
plugins: [esbuildDepPlugin(deps)],
});
}
Example #12
Source File: esbuild.ts From vue-components-lib-seed with MIT License | 6 votes |
async function run(options?: BuildOptions) {
await build({
outdir: `${cwd()}/dist/es`,
bundle: true,
entryPoints: componentEntrys,
plugins: [
vue({
sourceMap: false,
style: {
preprocessLang: 'styl',
// preprocessOptions: {
// stylus: {
// additionalData: `@import '${process.cwd()}/src/styles/index.styl'`,
// },
// },
},
}),
],
loader: { '.png': 'dataurl' },
external: [
'vue',
'my-lib/*',
'@vue/*',
'@better-scroll/*',
'jpeg-js',
],
format: 'esm',
minify: false,
...options,
})
}
Example #13
Source File: esbuild.ts From vue-components-lib-seed with MIT License | 6 votes |
/**
* @deprecated
*/
async function bundle(options?: BuildOptions) {
await build({
outfile: `${cwd()}/dist/es/my-lib.esm.js`,
bundle: true,
entryPoints: [`${cwd()}/src/packages/my-lib.ts`],
plugins: [vue()],
loader: { '.png': 'dataurl' },
external: ['vue', 'my-lib/*', '@vue/*'],
format: 'esm',
minify: true,
...options,
})
}
Example #14
Source File: esbuildBundler.ts From elderjs with MIT License | 4 votes |
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 #15
Source File: index.test.ts From esbuild-plugin-less with Do What The F*ck You Want To Public License | 4 votes |
describe('less-loader', () => {
it('exported module', () => {
expect(lessLoader).toBeDefined();
});
it('onResolve with watch mode', () => {
const plugin = lessLoader();
let onResolveCallback = null;
const build = {
initialOptions: {
watch: true,
},
onResolve: (opts, callback) => {
onResolveCallback = callback;
},
onStart: jest.fn(),
onEnd: jest.fn(),
onLoad: jest.fn(),
} as unknown as PluginBuild;
plugin.setup(build);
const path = '/path';
const onResolveResult = onResolveCallback({ resolveDir: '/', path });
expect(onResolveResult).toMatchObject({
path,
watchFiles: [path],
});
});
it('builds successful', async () => {
const primaryColor = '#ff0000';
const result = await buildLess({
lessOptions: {
globalVars: {
primaryColor,
},
},
});
expect(result.length).toStrictEqual(2);
expect(path.extname(result[0].path)).toStrictEqual('.js');
expect(path.extname(result[1].path)).toStrictEqual('.css');
// Result has compiled .less
const css = result[1].text;
expect(css).toMatch(`background:${primaryColor}`);
expect(css).toMatch(`body article{width:100px}`);
expect(css).toMatch(`body article:first-child{width:200px}`);
});
it('builds successful custom filter', async () => {
const primaryColor = '#ff0000';
const result = await buildLessWithOption({
lessOptions: {
globalVars: {
primaryColor,
},
},
loaderOptions: {
filter: /\._?less_?$/,
},
});
expect(result.length).toStrictEqual(2);
expect(path.extname(result[0].path)).toStrictEqual('.js');
expect(path.extname(result[1].path)).toStrictEqual('.css');
// Result has compiled .less
const css = result[1].text;
expect(css).toMatch(`background:${primaryColor}`);
expect(css).toMatch(`body article{width:100px}`);
expect(css).toMatch(`body article:first-child{width:200px}`);
});
it('builds imported .less files', async () => {
const result = await buildLess({
lessOptions: {
globalVars: {
primaryColor: '#ff0000',
},
},
});
const css = result[1].text;
expect(css).toMatch(`.style-2-less`);
expect(css).toMatch(`.style-3-less`);
});
it('builds imported ._less_ files', async () => {
const result = await buildLessWithOption({
lessOptions: {
globalVars: {
primaryColor: '#ff0000',
},
},
loaderOptions: {
filter: /\._?less_?$/,
},
});
const css = result[1].text;
expect(css).toMatch(`.style-2-less`);
expect(css).toMatch(`.style-3-less`);
});
it('builds imported .css files', async () => {
const result = await buildLess({
lessOptions: {
globalVars: {
primaryColor: '#ff0000',
},
},
});
const css = result[1].text;
expect(css).toMatch(`#style-4-css`);
expect(css).toMatch(`#style-5-css`);
});
it('catches less error', async () => {
await expect(
buildLess({
lessOptions: {
globalVars: {},
},
}),
).rejects.toThrow();
});
});