Skip to content

Commit

Permalink
fix: plugin-react 跳过node_modules下的编译导致未标识Island组件
Browse files Browse the repository at this point in the history
  • Loading branch information
c0dedance committed Nov 2, 2023
1 parent 4527b54 commit 56d4079
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 4 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"@babel/core": "^7.23.2",
"@babel/helper-plugin-utils": "^7.22.5",
"@babel/preset-react": "^7.22.15",
"@babel/preset-typescript": "^7.23.2",
"@babel/traverse": "^7.23.2",
"@mdx-js/rollup": "2.1.3",
"@types/react": "^18.2.31",
Expand Down
103 changes: 103 additions & 0 deletions pnpm-lock.yaml

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

32 changes: 32 additions & 0 deletions src/node/plugin-island/transform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { TransformOptions, transformAsync } from '@babel/core'
import babelPluginIsland from '../babel-plugin-island'
import type { Plugin } from 'vite'

const ISLAND_FILE_REGEX = (name) => name.endsWith('x') // island组件可能存在的文件.jsx | .tsx | .mdx
const ISLAND_CODE_REGEX = /(?<= )__island/

export function pluginTransformIslands(): Plugin {
return {
name: 'vite-plugin-transform-islands',
apply: 'build',
enforce: 'pre', // 需要最先处理一次
async transform(code, id) {
if (ISLAND_FILE_REGEX(id) && ISLAND_CODE_REGEX.test(code)) {
const res = await transformIslands(code, id)
return res
}
},
}
}

async function transformIslands(
code: string,
filename: string
): Promise<string> {
const babelOptions: TransformOptions = {
filename,
presets: ['@babel/preset-typescript'],
plugins: [babelPluginIsland],
}
return transformAsync(code, babelOptions)
}
9 changes: 5 additions & 4 deletions src/node/vitePlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { pluginIndexHtml } from './plugin-r-press/indexHtml'
import { pluginConfig } from './plugin-r-press/config'
import { pluginRoutes } from './plugin-routes'
import { createPluginMdx } from './plugin-mdx'
import babelPluginIsland from './babel-plugin-island'
import { pluginTransformIslands } from './plugin-island/transform'
import unocssOptions from './unocssOptions'
import { ROOT } from './constant'

Expand All @@ -19,12 +19,13 @@ export async function createVitePlugins(
return [
pluginUnocss(unocssOptions),
pluginIndexHtml(),
pluginTransformIslands(),
pluginReact({
jsxRuntime: 'automatic',
jsxImportSource: isSSR ? path.join(ROOT, 'src', 'runtime') : 'react',
babel: {
plugins: [babelPluginIsland],
},
// babel: {
// plugins: [babelPluginIsland],
// },
}),
pluginConfig(config, restartServer),
pluginRoutes({
Expand Down

0 comments on commit 56d4079

Please sign in to comment.