Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

Commit

Permalink
fix: dynamic import module to avoid breaking in browser (#129)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kingwl authored Mar 31, 2022
1 parent 55f5753 commit 33eb148
Show file tree
Hide file tree
Showing 10 changed files with 39 additions and 50 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ module.exports = {
```ts
import { transform } from 'unplugin-vue2-script-setup'

const Vue2SFC = transform(`
const Vue2SFC = await transform(`
<template>
<!-- ... -->
</template>
Expand Down
4 changes: 2 additions & 2 deletions jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ function requireVueJest() {
}

module.exports = {
process(source, filename, ...args) {
const transformed = transform(source, filename)
async process(source, filename, ...args) {
const transformed = await transform(source, filename)
const code = transformed ? transformed.code : source
return requireVueJest().process.call(this, code, filename, ...args)
},
Expand Down
10 changes: 3 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,6 @@
"require": "./dist/webpack.js",
"import": "./dist/webpack.mjs",
"types": "./webpack.d.ts"
},
"./lib": {
"require": "./dist/lib.js",
"import": "./dist/lib.mjs",
"types": "./lib.d.ts"
}
},
"main": "dist/index.js",
Expand Down Expand Up @@ -101,6 +96,7 @@
"@types/babel__core": "^7.1.18",
"@types/estree": "^0.0.51",
"@types/node": "^17.0.21",
"@types/pug": "^2.0.6",
"@types/ws": "^8.5.0",
"@vue/composition-api": "^1.4.6",
"@vue/runtime-dom": "^3.2.31",
Expand All @@ -117,9 +113,9 @@
"vitest": "0.5.4"
},
"peerDependencies": {
"pug": "^3.0.2",
"@vue/composition-api": "^1.4.3",
"@vue/runtime-dom": "^3.2.31"
"@vue/runtime-dom": "^3.2.31",
"pug": "^3.0.2"
},
"peerDependenciesMeta": {
"pug": {
Expand Down
8 changes: 7 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ const entries = [
'src/vite.ts',
'src/rollup.ts',
'src/esbuild.ts',
'src/nuxt.ts',
'src/lib.ts',
'src/nuxt.ts'
]

const dtsEntries = [
Expand Down
15 changes: 3 additions & 12 deletions src/core/parseSFC.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable one-var */
/* eslint-disable @typescript-eslint/no-namespace */
import { createRequire } from 'module'
import { notNullish, partition } from '@antfu/utils'
import type { Program } from '@babel/types'
import type { ParserPlugin } from '@babel/parser'
Expand Down Expand Up @@ -83,14 +82,6 @@ const BUILD_IN_DIRECTIVES = new Set([
// 'ref',
])

function getRequire() {
return (
(typeof require === 'function')
? require
: createRequire(import.meta.url)
)
}

function getComponents(node: TemplateChildNode): string[] {
const current
= node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.COMPONENT
Expand Down Expand Up @@ -282,11 +273,11 @@ function getBabelParserOptions(lang: string | null | undefined) {
plugins,
}
}
export function parseSFC(
export async function parseSFC(
code: string,
id?: string,
options?: ScriptSetupTransformOptions,
): ParsedSFC {
): Promise<ParsedSFC> {
const elementChildren = baseParse(code, parserOptions).children.flatMap(x =>
x.type === NodeTypes.ELEMENT && x.tagType === ElementTypes.ELEMENT
? [x]
Expand Down Expand Up @@ -376,7 +367,7 @@ export function parseSFC(
&& p.value.content === 'pug',
)
? baseParse(
getRequire()('pug').compile(
(await import('pug')).compile(
templateNode.children.map(x => x.loc.source).join(''),
{
filename: id,
Expand Down
8 changes: 4 additions & 4 deletions src/core/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ export function shouldTransform(code: string, id: string, options?: ScriptSetupT
return (options?.reactivityTransform && shouldTransformRefSugar(code)) || scriptSetupRE.test(code)
}

export function transform(input: string, id: string, options?: ScriptSetupTransformOptions): TransformResult {
export async function transform(input: string, id: string, options?: ScriptSetupTransformOptions): Promise<TransformResult> {
if (!shouldTransform(input, id, options))
return null
const resolved = resolveOptions(options)
if (id.endsWith('.vue') || id.includes('.vue?vue'))
return transformVue(input, id, resolved)
return await transformVue(input, id, resolved)
else
return transformNonVue(input, id, resolved)
}
Expand All @@ -36,10 +36,10 @@ function transformNonVue(input: string, id: string, options: ResolvedOptions): T
return null
}

function transformVue(input: string, id: string, options: ResolvedOptions): TransformResult {
async function transformVue(input: string, id: string, options: ResolvedOptions): Promise<TransformResult> {
const s = new MagicString(input)

const sfc = parseSFC(input, id)
const sfc = await parseSFC(input, id)

if (options.reactivityTransform)
transformSfcRefSugar(sfc, options)
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ export const unplugin = createUnplugin<PluginOptions>((options = {}) => {
transformInclude(id) {
return filter(id)
},
transform(code, id) {
async transform(code, id) {
try {
return transform(code, id, options)
return await transform(code, id, options)
}
catch (e: any) {
this.error(e)
Expand Down
31 changes: 14 additions & 17 deletions test/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest'
import { transform as t } from '../src'

describe('errors', () => {
it('langs', () => {
expect(() =>
it('langs', async() => {
await expect(() =>
t(`
<script setup>
const a = 1
Expand All @@ -12,54 +12,51 @@ const a = 1
<script lang="ts">
export default {}
</script>
`, 'Lang.vue'))
.toThrowError('<script setup> language must be the same as <script>')
`, 'Lang.vue')).rejects.toThrowError('<script setup> language must be the same as <script>')
})

it('defineProps', () => {
expect(() =>
it('defineProps', async() => {
await expect(() =>
t(`
<script setup>
defineProps()
const a = defineProps()
</script>
`, 'DefineProps.vue'))
.toThrowError('duplicate defineProps() call')
.rejects.toThrowError('duplicate defineProps() call')
})

it('top-level await', () => {
expect(() =>
it('top-level await', async() => {
await expect(() =>
t(`
<script setup>
defineProps()
await something()
</script>
`, 'TopLevel.vue'))
.toThrowError('top-level await is not supported in Vue 2')
.rejects.toThrowError('top-level await is not supported in Vue 2')

expect(() =>
await expect(() =>
t(`
<script setup>
defineProps()
const {data} = await something()
</script>
`, 'TopLevel.vue'))
.toThrowError('top-level await is not supported in Vue 2')
.rejects.toThrowError('top-level await is not supported in Vue 2')
})

it('ref sugar', () => {
it('ref sugar', async() => {
const consoleWarnMock = vi.spyOn(console, 'warn')

expect(() =>
t(`
await t(`
<script setup>
defineProps()
const a = async () => {
await something()
}
</script>
`, 'App.vue'))
.not.toThrow()
`, 'App.vue')

consoleWarnMock.mockRestore()
})
Expand Down
4 changes: 2 additions & 2 deletions test/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ describe('transform', () => {
for (const file of files) {
it(file.replace(/\\/g, '/'), async() => {
const fixture = await fs.readFile(resolve(root, file), 'utf-8')
const result = transform(fixture, file, { reactivityTransform: true })?.code || fixture
const result = (await transform(fixture, file, { reactivityTransform: true }))?.code || fixture
expect(result).toMatchSnapshot()

const result2 = transform(result, file, { reactivityTransform: true })?.code || result
const result2 = (await transform(result, file, { reactivityTransform: true }))?.code || result
expect(result).toEqual(result2)
})
}
Expand Down

0 comments on commit 33eb148

Please sign in to comment.