rsnext/packages/next/build/webpack/loaders/utils.ts
Jiachi Liu 4e8e191a6e
RSC: handle commonjs in flight loader (#35563)
We need to handle cjs cases for client/server components when they're compiled to commonjs in some cases.
e.g. if there's an internal `_app.server.js` in nextjs, the assets in the dist files are compiled to cjs by swc. Or any 3rd party libraries are consumed could be cjs only.

### How it works

* Detect the source file is ESM or CJS first by detect if there's any ESM import/export
* Append the new exports or collect exports info based on the module type
2022-03-25 21:17:33 +00:00

21 lines
586 B
TypeScript

export function buildExports(moduleExports: any, isESM: boolean) {
let ret = ''
Object.keys(moduleExports).forEach((key) => {
const exportExpression = isESM
? `export ${key === 'default' ? key : `const ${key} =`} ${
moduleExports[key]
}`
: `exports.${key} = ${moduleExports[key]}`
ret += exportExpression + '\n'
})
return ret
}
const esmNodeTypes = [
'ImportDeclaration',
'ExportNamedDeclaration',
'ExportDefaultExpression',
'ExportDefaultDeclaration',
]
export const isEsmNodeType = (type: string) => esmNodeTypes.includes(type)