fix(bridge): default export detection (#1774)

This commit is contained in:
Anthony Fu 2021-11-08 18:33:42 +08:00 committed by GitHub
parent c676493011
commit 39db33d625
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,12 +1,11 @@
import type { Plugin } from 'vite' import type { Plugin } from 'vite'
import fse from 'fs-extra' import fse from 'fs-extra'
import { findExports } from 'mlly'
// const PREFIX = 'defaultexport:'
const PREFIX = 'defaultexport:' const PREFIX = 'defaultexport:'
const hasPrefix = (id: string = '') => id.startsWith(PREFIX) const hasPrefix = (id: string = '') => id.startsWith(PREFIX)
const removePrefix = (id: string = '') => hasPrefix(id) ? id.substr(PREFIX.length) : id const removePrefix = (id: string = '') => hasPrefix(id) ? id.substr(PREFIX.length) : id
const hasDefaultExport = (code: string = '') => code.includes('export default')
const addDefaultExport = (code: string = '') => code + '\n\n' + 'export default () => {}' const addDefaultExport = (code: string = '') => code + '\n\n' + 'export default () => {}'
export function defaultExportPlugin () { export function defaultExportPlugin () {
@ -26,7 +25,8 @@ export function defaultExportPlugin () {
async load (id) { async load (id) {
if (hasPrefix(id)) { if (hasPrefix(id)) {
let code = await fse.readFile(removePrefix(id), 'utf8') let code = await fse.readFile(removePrefix(id), 'utf8')
if (!hasDefaultExport(code)) { const exports = findExports(code)
if (!exports.find(i => i.type === 'default' || i.name === 'default')) {
code = addDefaultExport(code) code = addDefaultExport(code)
} }
return { map: null, code } return { map: null, code }