Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support format config #238

Merged
merged 3 commits into from
Oct 12, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: support format config
  • Loading branch information
zce committed Oct 12, 2024
commit b0ca8112c0536bddd5002664d0af9bd03ad90877
2 changes: 1 addition & 1 deletion src/build.ts
Original file line number Diff line number Diff line change
@@ -273,7 +273,7 @@ export const build = async (options: Options = {}): Promise<Record<string, unkno
await mkdir(output.data, { recursive: true })
await mkdir(output.assets, { recursive: true })

await outputEntry(output.data, configPath, collections)
await outputEntry(output.data, output.format, configPath, collections)

logger.log('initialized', begin)

3 changes: 2 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
@@ -108,7 +108,8 @@ export const resolveConfig = async (path?: string, options: { strict?: boolean;
assets: resolve(cwd, loadedConfig.output?.assets ?? 'public/static'),
base: loadedConfig.output?.base ?? '/static/',
name: loadedConfig.output?.name ?? '[name]-[hash:8].[ext]',
clean: options.clean ?? loadedConfig.output?.clean ?? false
clean: options.clean ?? loadedConfig.output?.clean ?? false,
format: loadedConfig.output?.format ?? 'esm'
},
loaders: [...(loadedConfig.loaders ?? []), ...loaders],
strict: options.strict ?? loadedConfig.strict ?? false
22 changes: 13 additions & 9 deletions src/output.ts
Original file line number Diff line number Diff line change
@@ -3,7 +3,9 @@ import { join, relative } from 'node:path'

import { logger } from './logger'

import type { Collections } from './types'
import type { Collections, Output } from './types'

const isProduction = process.env.NODE_ENV === 'production'

const emitted = new Map<string, string>()

@@ -29,20 +31,21 @@ export const emit = async (path: string, content: string, log?: string): Promise
* @param configPath resolved config file path
* @param collections collection options
*/
export const outputEntry = async (dest: string, configPath: string, collections: Collections): Promise<void> => {
export const outputEntry = async (dest: string, format: Output['format'], configPath: string, collections: Collections): Promise<void> => {
const begin = performance.now()

// generate entry according to `config.collections`
const configModPath = relative(dest, configPath)
.replace(/\\/g, '/') // replace windows path separator
.replace(/\.[mc]?[jt]s$/i, '') // remove extension
const configModPath = relative(dest, configPath).replace(/\\/g, '/')

const entry: string[] = []
const dts: string[] = [`import config from '${configModPath}'\n`]
const dts: string[] = [`import type config from '${configModPath}'\n`]
dts.push('type Collections = typeof config.collections\n')

Object.entries(collections).map(([name, collection]) => {
entry.push(`export { default as ${name} } from './${name}.json'`)
if (format === 'cjs') {
entry.push(`exports.${name} = require('./${name}.json')`)
} else {
entry.push(`export { default as ${name} } from './${name}.json'`)
}
Comment on lines +44 to +48
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate the format parameter to ensure robustness

Currently, the code conditionally handles 'cjs' and defaults to ES module syntax for other values of format. To prevent potential issues with unexpected format values, consider validating the format parameter and providing a default or throwing an error for unsupported formats.

You could implement a validation mechanism like this:

 export const outputEntry = async (dest: string, format: Output['format'], configPath: string, collections: Collections): Promise<void> => {
+  if (!['cjs', 'esm'].includes(format)) {
+    throw new Error(`Unsupported format '${format}'. Expected 'cjs' or 'esm'.`)
+  }
   const begin = performance.now()

This ensures that only supported formats are processed and helps catch configuration errors early.

Committable suggestion was skipped due to low confidence.

dts.push(`export type ${collection.name} = Collections['${name}']['schema']['_output']`)
dts.push(`export declare const ${name}: ${collection.name + (collection.single ? '' : '[]')}\n`)
})
@@ -71,7 +74,8 @@ export const outputData = async (dest: string, result: Record<string, any>): Pro
if (data == null) return
const target = join(dest, name + '.json')
// TODO: output each record separately to a single file to improve fast refresh performance in app
await emit(target, JSON.stringify(data, null, 2), `wrote '${target}' with ${data.length ?? 1} ${name}`)
const content = isProduction ? JSON.stringify(data) : JSON.stringify(data, null, 2)
await emit(target, content, `wrote '${target}' with ${data.length ?? 1} ${name}`)
logs.push(`${data.length ?? 1} ${name}`)
})
)
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -141,6 +141,11 @@ export interface Output {
* @default false
*/
clean: boolean
/**
* Output entry file format
* @default 'esm'
*/
format: 'esm' | 'cjs'
}

/**