@@ -3,7 +3,9 @@ import { join, relative } from 'node:path'
33
44import { logger } from './logger'
55
6- import type { Collections } from './types'
6+ import type { Collections , Output } from './types'
7+
8+ const isProduction = process . env . NODE_ENV === 'production'
79
810const emitted = new Map < string , string > ( )
911
@@ -29,20 +31,21 @@ export const emit = async (path: string, content: string, log?: string): Promise
2931 * @param configPath resolved config file path
3032 * @param collections collection options
3133 */
32- export const outputEntry = async ( dest : string , configPath : string , collections : Collections ) : Promise < void > => {
34+ export const outputEntry = async ( dest : string , format : Output [ 'format' ] , configPath : string , collections : Collections ) : Promise < void > => {
3335 const begin = performance . now ( )
3436
35- // generate entry according to `config.collections`
36- const configModPath = relative ( dest , configPath )
37- . replace ( / \\ / g, '/' ) // replace windows path separator
38- . replace ( / \. [ m c ] ? [ j t ] s $ / i, '' ) // remove extension
37+ const configModPath = relative ( dest , configPath ) . replace ( / \\ / g, '/' )
3938
4039 const entry : string [ ] = [ ]
41- const dts : string [ ] = [ `import config from '${ configModPath } '\n` ]
40+ const dts : string [ ] = [ `import type config from '${ configModPath } '\n` ]
4241 dts . push ( 'type Collections = typeof config.collections\n' )
4342
4443 Object . entries ( collections ) . map ( ( [ name , collection ] ) => {
45- entry . push ( `export { default as ${ name } } from './${ name } .json'` )
44+ if ( format === 'cjs' ) {
45+ entry . push ( `exports.${ name } = require('./${ name } .json')` )
46+ } else {
47+ entry . push ( `export { default as ${ name } } from './${ name } .json'` )
48+ }
4649 dts . push ( `export type ${ collection . name } = Collections['${ name } ']['schema']['_output']` )
4750 dts . push ( `export declare const ${ name } : ${ collection . name + ( collection . single ? '' : '[]' ) } \n` )
4851 } )
@@ -71,7 +74,8 @@ export const outputData = async (dest: string, result: Record<string, any>): Pro
7174 if ( data == null ) return
7275 const target = join ( dest , name + '.json' )
7376 // TODO: output each record separately to a single file to improve fast refresh performance in app
74- await emit ( target , JSON . stringify ( data , null , 2 ) , `wrote '${ target } ' with ${ data . length ?? 1 } ${ name } ` )
77+ const content = isProduction ? JSON . stringify ( data ) : JSON . stringify ( data , null , 2 )
78+ await emit ( target , content , `wrote '${ target } ' with ${ data . length ?? 1 } ${ name } ` )
7579 logs . push ( `${ data . length ?? 1 } ${ name } ` )
7680 } )
7781 )
0 commit comments