Skip to content
This repository has been archived by the owner on Sep 6, 2023. It is now read-only.

Commit

Permalink
feat: support CJS + ESM for @wagmi/chains (#97)
Browse files Browse the repository at this point in the history
* feat: support cjs on @wagmi/chains

* chore: changeset

* update

* Update .changeset/spotty-tomatoes-matter.md

---------

Co-authored-by: awkweb <tom@meagher.co>
  • Loading branch information
jxom and tmm authored Feb 3, 2023
1 parent 5ed73ed commit bbbc91e
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 23 deletions.
5 changes: 5 additions & 0 deletions .changeset/spotty-tomatoes-matter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@wagmi/chains': patch
---

Added support for both CJS + ESM for `@wagmi/chains`
3 changes: 2 additions & 1 deletion packages/chains/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"description": "A collection of chains for wagmi",
"license": "MIT",
"version": "0.2.5",
"type": "module",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsup",
Expand All @@ -13,6 +13,7 @@
"exports": {
".": {
"types": "./dist/index.d.ts",
"module": "./dist/index.mjs",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
Expand Down
10 changes: 8 additions & 2 deletions scripts/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ function prepare({ packages }: { packages: Package[] }) {
const oldPackageJson = { ...packageJson }

delete packageJson.type
delete packageJson.module
delete packageJson.exports
writeJsonSync(packageJsonPath, packageJson, { spaces: 2 })

preparedPackages.push({ dir: packageDir, oldPackageJson, packageJson })
Expand Down Expand Up @@ -88,7 +90,9 @@ function version({ changedPackages }: { changedPackages: Package[] }) {
for (const { dir, packageJson } of changedPackages) {
const newPackageJson = { ...packageJson }
newPackageJson.version = packageJson.version + '-cjs'
writeJsonSync(path.join(dir, 'package.json'), newPackageJson, { spaces: 2 })
writeJsonSync(path.join(dir, 'package.json'), newPackageJson, {
spaces: 2,
})
}
}

Expand All @@ -114,6 +118,8 @@ function postPublish({
}) {
// Restore package.jsons
for (const { oldPackageJson, dir } of preparedPackages) {
writeJsonSync(path.join(dir, 'package.json'), oldPackageJson, { spaces: 2 })
writeJsonSync(path.join(dir, 'package.json'), oldPackageJson, {
spaces: 2,
})
}
}
77 changes: 57 additions & 20 deletions scripts/tsup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,20 @@ export function getConfig({ dev, ...options }: GetConfig): Options {
if (!options.entry?.length) throw new Error('entry is required')
const entry: string[] = options.entry ?? []

const packageJson = fs.readJsonSync('package.json')
let format: Format[] = ['cjs']
if (packageJson.type === 'module') format = ['esm']
if (packageJson.module) format.push('esm')
if (process.env.FORMAT as Format) format = [process.env.FORMAT as Format]

// Hacks tsup to create Preconstruct-like linked packages for development
// https://github.com/preconstruct/preconstruct
if (dev)
return {
clean: true,
// Only need to generate one file with tsup for development since we will create links in `onSuccess`
entry: [entry[0] as string],
format: [(process.env.FORMAT as Format) ?? 'esm'],
format,
silent: true,
async onSuccess() {
// remove all files in dist
Expand All @@ -47,26 +53,33 @@ export function getConfig({ dev, ...options }: GetConfig): Options {
distSourceFile.replace(/\.js$/, '.d.ts'),
`export * from '${srcTypesFile}'`,
)
if (format.includes('esm') && format.includes('cjs'))
fs.copyFileSync(
distSourceFile,
distSourceFile.replace('.js', '.mjs'),
)
}
const exports = await generateExports(entry)
await generateProxyPackages(exports)
await validateExports(exports)
const exports = await generateExports(entry, { format })
await generateProxyPackages(exports, { format })
if (format.includes('esm')) await validateExports(exports)
},
}

return {
bundle: true,
clean: true,
dts: true,
format: [(process.env.FORMAT as Format) ?? 'esm'],
format,
splitting: true,
target: 'es2021',
async onSuccess() {
if (typeof options.onSuccess === 'function') await options.onSuccess()
else if (typeof options.onSuccess === 'string') execa(options.onSuccess)

const exports = await generateExports(entry)
await generateProxyPackages(exports)
const exports = await generateExports(entry, { format })
await generateProxyPackages(exports, { format })

if (!format.includes('esm')) return
try {
await validateExports(exports)
} catch (error) {
Expand All @@ -91,13 +104,16 @@ export function getConfig({ dev, ...options }: GetConfig): Options {
}

type Exports = {
[key: string]: string | { types?: string; default: string }
[key: string]: string | { types?: string; module?: string; default: string }
}

/**
* Generate exports from entry files
*/
async function generateExports(entry: string[]) {
async function generateExports(
entry: string[],
{ format }: { format?: Format[] },
) {
const exports: Exports = {}
for (const file of entry) {
const extension = path.extname(file)
Expand All @@ -113,9 +129,17 @@ async function generateExports(entry: string[]) {
/^src\//g,
'./dist/',
)}.d.ts`
exports[name] = {
types: distTypesFile,
default: distSourceFile,
if (format?.includes('cjs')) {
exports[name] = {
types: distTypesFile,
module: distSourceFile.replace('.js', '.mjs'),
default: distSourceFile,
}
} else {
exports[name] = {
types: distTypesFile,
default: distSourceFile,
}
}
}

Expand Down Expand Up @@ -150,7 +174,10 @@ async function validateExports(exports: Exports) {
/**
* Generate proxy packages files for each export
*/
async function generateProxyPackages(exports: Exports) {
async function generateProxyPackages(
exports: Exports,
{ format }: { format?: Format[] },
) {
const ignorePaths = []
const files = new Set<string>()
for (const [key, value] of Object.entries(exports)) {
Expand All @@ -165,13 +192,23 @@ async function generateProxyPackages(exports: Exports) {
`Proxy package "${key}" entrypoint "${entrypoint}" does not exist.`,
)

await fs.outputFile(
`${key}/package.json`,
dedent`{
"type": "module",
"main": "${entrypoint}"
}`,
)
if (format?.includes('cjs')) {
await fs.outputFile(
`${key}/package.json`,
dedent`{
"module": "${entrypoint.replace('.js', '.mjs')}",
"main": "${entrypoint}"
}`,
)
} else {
await fs.outputFile(
`${key}/package.json`,
dedent`{
"type": "module",
"main": "${entrypoint}"
}`,
)
}
ignorePaths.push(key.replace(/^\.\//g, ''))

const file = key.replace(/^\.\//g, '').split('/')[0]
Expand Down

0 comments on commit bbbc91e

Please sign in to comment.