Skip to content

Commit

Permalink
fix: support cjs stubbing (#220)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Aug 24, 2021
1 parent 638fe75 commit c61f314
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
27 changes: 18 additions & 9 deletions src/core/package/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,33 @@ describe('package class', () => {
// TODO: move to fixture
test('should generate package stub', async () => {
const defaultPath = getFixturePath('default')
const files = [
resolve(defaultPath, 'dist/index.js'),
resolve(defaultPath, 'dist/index.es.js'),
resolve(defaultPath, 'dist/index.d.ts'),
]
for (const file of files) {
const files = {
[resolve(defaultPath, 'dist/index.js')]: [
`const jiti = require('jiti')()`,
`module.exports = jiti('./../src/index')`,
].join('\n'),
[resolve(
defaultPath,
'dist/index.es.js'
)]: `export * from './../src/index'`,
[resolve(
defaultPath,
'dist/index.d.ts'
)]: `export * from './../src/index'`,
}
for (const file in files) {
await remove(file)
expect(existsSync(file)).toBeFalsy()
}

await core.createStubs()

for (const file of files) {
for (const file in files) {
expect(
readFileSync(file)
.toString()
.replace(/from '.*\/fixture/, "from '/fixture")
).toBe(`export * from './../src/index'`)
.replace(/'.*\/fixture/, "'/fixture")
).toBe(files[file])
}
})

Expand Down
21 changes: 16 additions & 5 deletions src/core/package/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,29 +342,40 @@ export class Package {
const absPath = entrypoint.replace(/(\.[jt]s)$/, '')
await writeFile(
binary,
`#!/usr/bin/env node\nconst jiti = require('jiti')()\nmodule.exports = jiti('${absPath}')`
[
`#!/usr/bin/env node`,
`const jiti = require('jiti')()`,
`module.exports = jiti('${absPath}')`,
].join('\n')
)
await this.setBinaryPermissions()
})
}

async createStub(path: string | undefined) {
async createStub(path: string | undefined, cjs = false) {
if (!path || !this.entrypoint || !this.options.build) return

const outFile = this.resolvePath(path)
const outDir = dirname(outFile)
if (!existsSync(outDir)) await mkdirp(outDir)
const relativeEntrypoint = relative(outDir, this.entrypoint).replace(
/(\.[jt]s)$/,
/(\.[cm]?[jt]s)$/,
''
)
await writeFile(outFile, `export * from './${relativeEntrypoint}'`)
const stub = cjs
? [
`const jiti = require('jiti')()`,
`module.exports = jiti('./${relativeEntrypoint}')`,
].join('\n')
: `export * from './${relativeEntrypoint}'`

await writeFile(outFile, stub)
}

async createStubs() {
return Promise.all([
this.createBinaryStubs(),
this.createStub(this.pkg.main),
this.createStub(this.pkg.main, true),
this.createStub(this.pkg.module),
this.createStub(this.pkg.types),
])
Expand Down

0 comments on commit c61f314

Please sign in to comment.