Skip to content

Commit

Permalink
add build script to make things work everywhere
Browse files Browse the repository at this point in the history
Just coppying other people's hack go to make a build ts project work on cjs and esm
  • Loading branch information
meech-ward committed Oct 14, 2024
1 parent 2019ad5 commit d439ab2
Show file tree
Hide file tree
Showing 7 changed files with 996 additions and 342 deletions.
84 changes: 84 additions & 0 deletions build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
This script was taken from hono https://github.com/honojs/hono/blob/main/build.ts
Everything below is theres
*/
/*
This script is heavily inspired by `built.ts` used in @kaze-style/react.
https://github.com/taishinaritomi/kaze-style/blob/main/scripts/build.ts
MIT License
Copyright (c) 2022 Taishi Naritomi
*/

import { exec } from 'child_process'
import fs from 'fs'
import path from 'path'
import { build } from 'esbuild'
import type { Plugin, PluginBuild, BuildOptions } from 'esbuild'
import glob from 'glob'



const entryPoints = glob.sync('./src/**/*.ts', {
ignore: ['./src/**/*.test.ts', './src/mod.ts', './src/middleware.ts', './src/deno/**/*.ts'],
})

/*
This plugin is inspired by the following.
https://github.com/evanw/esbuild/issues/622#issuecomment-769462611
*/
const addExtension = (extension: string = '.js', fileExtension: string = '.ts'): Plugin => ({
name: 'add-extension',
setup(build: PluginBuild) {
build.onResolve({ filter: /.*/ }, (args) => {
if (args.importer) {
const p = path.join(args.resolveDir, args.path)
let tsPath = `${p}${fileExtension}`

let importPath = ''
if (fs.existsSync(tsPath)) {
importPath = args.path + extension
} else {
tsPath = path.join(args.resolveDir, args.path, `index${fileExtension}`)
if (fs.existsSync(tsPath)) {
if (args.path.endsWith('/')) {
importPath = `${args.path}index${extension}`
} else {
importPath = `${args.path}/index${extension}`
}
}
}
return { path: importPath, external: true }
}
})
},
})

const commonOptions: BuildOptions = {
entryPoints,
logLevel: 'info',
platform: 'node',
tsconfig: 'tsconfig.json',
}

const cjsBuild = () =>
build({
...commonOptions,
outbase: './src',
outdir: './dist/cjs',
format: 'cjs',
tsconfig: 'tsconfig.cjs.json',
})

const esmBuild = () =>
build({
...commonOptions,
bundle: true,
outbase: './src',
outdir: './dist',
format: 'esm',
plugins: [addExtension('.js')],
})

Promise.all([esmBuild(), cjsBuild()])

exec(`tsc --emitDeclarationOnly --declaration --project tsconfig.build.json`)
Loading

0 comments on commit d439ab2

Please sign in to comment.