Skip to content

Commit c4bc8ae

Browse files
authored
feat: use module syntax if target file looks like esm (#21)
1 parent 5bf37b6 commit c4bc8ae

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

lib/aliases.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,21 @@ module.exports = function (rootDir) {
3535
}
3636

3737
const sourceJsPath = findSource(rootDir, source)
38+
const sourceRaw = fs.readFileSync(sourceJsPath).toString()
39+
// eslint-disable-next-line unicorn/prefer-starts-ends-with
40+
const maybeIsEsm = sourceRaw.match(/^export /m)
3841
const sourceDTsPath = sourceJsPath.replace(/\.js$/, '.d.ts')
3942
const destJsPath = path.join(rootDir, alias + '.js')
4043
const destDTsPath = path.join(rootDir, alias + '.d.ts')
4144
if (fs.existsSync(sourceDTsPath)) {
4245
fs.writeFileSync(destDTsPath, `export * from '${source}'\n`, 'utf8')
4346
}
4447

45-
return fs.writeFileAsync(destJsPath, `module.exports = require("${source}")\n`, 'utf8')
48+
const contents = maybeIsEsm ?
49+
`export * from "${source}"\n` :
50+
`module.exports = require("${source}")\n`
51+
52+
return fs.writeFileAsync(destJsPath, contents, 'utf8')
4653
},
4754
}
4855
}

test/aliases.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ describe('lib/aliases.js', () => {
5252
})
5353
})
5454

55+
it('should create an esm file when source looks like esm', () => {
56+
return aliasUtils(app1Dir).createAlias('lib/fileB.esm.js', 'alias').then(() => {
57+
return Promise.try(() => {
58+
const contents = fs.readFileSync(app1Dir + '/alias.js', 'utf8')
59+
contents.should.match(/^export \* from/)
60+
fs.unlinkSync(app1Dir + '/alias.js')
61+
})
62+
})
63+
})
64+
5565
it('should point the alias to the source file', () => {
5666
return aliasUtils(app3Dir).createAlias('./file.js', 'alias').then(() => {
5767
return Promise.try(() => {

test/fixtures/app1/lib/fileB.esm.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export function helloWorld() {};

0 commit comments

Comments
 (0)