提交 b7ee76de 编写于 作者: fxy060608's avatar fxy060608

feat(h5): support jsx, tsx

上级 48aa6baa
......@@ -13,4 +13,5 @@ packages/uni-mp-qq/lib
packages/uni-mp-toutiao/lib
packages/uni-mp-vue/lib
packages/uni-mp-weixin/lib
packages/uni-mp-quickapp-webview/lib
\ No newline at end of file
packages/uni-mp-quickapp-webview/lib
packages/vite-plugin-uni/lib
\ No newline at end of file
......@@ -5,9 +5,9 @@ export const EXTNAME_VUE_RE = /\.(vue|nvue)$/
export const EXTNAME_JS_RE = /\.[jt]sx?$/
// APP 平台解析页面后缀的优先级
export const PAGE_EXTNAME_APP = ['.nvue', '.vue']
export const PAGE_EXTNAME_APP = ['.nvue', '.vue', '.tsx', '.jsx', '.js']
// 其他平台解析页面后缀的优先级
export const PAGE_EXTNAME = ['.vue', '.nvue']
export const PAGE_EXTNAME = ['.vue', '.nvue', '.tsx', '.jsx', '.js']
export const H5_API_STYLE_PATH = '@dcloudio/uni-h5/style/api/'
export const H5_FRAMEWORK_STYLE_PATH = '@dcloudio/uni-h5/style/framework/'
......
......@@ -29,7 +29,7 @@ import { Alias } from 'types/alias'
import { transform, formatMessages } from 'esbuild'
import { resolveMainPathOnce } from '../../../../utils'
import { EXTNAME_VUE_RE } from '../../../../constants'
import { EXTNAME_JS_RE, EXTNAME_VUE_RE } from '../../../../constants'
// const debug = createDebugger('vite:css')
export interface CSSOptions {
......@@ -182,7 +182,10 @@ function normalizeCssChunkFilename(id: string) {
return normalizePath(
path.relative(
process.env.UNI_INPUT_DIR,
id.split('?')[0].replace(EXTNAME_VUE_RE, '.css')
id
.split('?')[0]
.replace(EXTNAME_VUE_RE, '.css')
.replace(EXTNAME_JS_RE, '.css')
)
)
}
......
import path from 'path'
import debug from 'debug'
import { Plugin } from 'vite'
import { normalizePath, parseVueRequest } from '@dcloudio/uni-cli-shared'
import {
EXTNAME_JS_RE,
normalizePath,
parseVueRequest,
} from '@dcloudio/uni-cli-shared'
const debugSetup = debug('vite:uni:setup')
......@@ -25,10 +29,16 @@ export function uniSetupPlugin(): Plugin {
}
if (query.mpType === 'page') {
debugSetup(filename)
return (
code +
`;import { setupPage } from '@dcloudio/uni-h5';setupPage(_sfc_main);`
)
// js,ts,jsx,tsx
const isJs = EXTNAME_JS_RE.test(filename)
if (isJs) {
code = code.replace(/export\s+default/, 'const _sfc_main =')
}
code += `;import { setupPage } from '@dcloudio/uni-h5';setupPage(_sfc_main);`
if (isJs) {
code += ';export default _sfc_main;'
}
return code
}
},
}
......
## [1.1.8](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.7...plugin-vue-jsx@1.1.8) (2021-09-07)
### Bug Fixes
* hmr doesn't work when modifying the code of jsx in sfc ([#4563](https://github.com/vitejs/vite/issues/4563)) ([1012367](https://github.com/vitejs/vite/commit/101236794c5d6d28591302d5552cb1c0ab8f4115))
## [1.1.7](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.6...plugin-vue-jsx@1.1.7) (2021-07-27)
### Bug Fixes
* **deps:** update all non-major dependencies ([#4387](https://github.com/vitejs/vite/issues/4387)) ([2f900ba](https://github.com/vitejs/vite/commit/2f900ba4d4ad8061e0046898e8d1de3129e7f784))
## [1.1.6](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.5...plugin-vue-jsx@1.1.6) (2021-06-27)
### Bug Fixes
* **deps:** update all non-major dependencies ([#3791](https://github.com/vitejs/vite/issues/3791)) ([74d409e](https://github.com/vitejs/vite/commit/74d409eafca8d74ec4a6ece621ea2895bc1f2a32))
* **plugin-vue-jsx:** replace default export with helper during SSR ([#3966](https://github.com/vitejs/vite/issues/3966)) ([bc86464](https://github.com/vitejs/vite/commit/bc86464d3c6591eae96e070a1724a3f21874c8ce))
* **ssr:** normalize manifest filenames ([#3706](https://github.com/vitejs/vite/issues/3706)) ([aa8ca3f](https://github.com/vitejs/vite/commit/aa8ca3f35218c9fb48f87d3f6f4681d379ee45ca)), closes [#3303](https://github.com/vitejs/vite/issues/3303)
### Features
* **plugin-vue-jsx:** jsx plugin should have extra babel plugins option ([#3923](https://github.com/vitejs/vite/issues/3923)) ([aada0c5](https://github.com/vitejs/vite/commit/aada0c5e71e4826cf049596f3459d48b386ea4da))
## [1.1.5](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.4...plugin-vue-jsx@1.1.5) (2021-06-01)
### Bug Fixes
* include/exclude options for vue-jsx .d.ts ([#3573](https://github.com/vitejs/vite/issues/3573)) ([82ec0ca](https://github.com/vitejs/vite/commit/82ec0ca69c1f077cf518073edca4e6580ebd4892))
## [1.1.4](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.3...plugin-vue-jsx@1.1.4) (2021-05-03)
### Features
* include/exclude options for vue-jsx plugin ([#1953](https://github.com/vitejs/vite/issues/1953)) ([fbecf1e](https://github.com/vitejs/vite/commit/fbecf1e5349ea5da8ff6f194efdcb152e2995398))
## [1.1.3](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.2...plugin-vue-jsx@1.1.3) (2021-03-31)
### Bug Fixes
* ignore babelrc ([#2766](https://github.com/vitejs/vite/issues/2766)) ([23c4114](https://github.com/vitejs/vite/commit/23c41149ddf74261f7615d22e59b39a017b79509)), closes [#2722](https://github.com/vitejs/vite/issues/2722)
## [1.1.2](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.1...plugin-vue-jsx@1.1.2) (2021-02-24)
## [1.1.1](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.0...plugin-vue-jsx@1.1.1) (2021-02-24)
### Bug Fixes
* **plugin-vue-jsx:** do not read babel configuration ([#2181](https://github.com/vitejs/vite/issues/2181)) ([8f0dc25](https://github.com/vitejs/vite/commit/8f0dc25e943ff490eefa0ed3663205a14e8eed9e))
# [1.1.0](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.3...plugin-vue-jsx@1.1.0) (2021-02-09)
### Features
* **plugin-vue-jsx:** register jsx module during ssr ([7a6aa2a](https://github.com/vitejs/vite/commit/7a6aa2ad2689bf8221389924a608876866db7b0a))
## [1.0.3](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.2...plugin-vue-jsx@1.0.3) (2021-02-08)
### Bug Fixes
* **plugin-vue-jsx:** support ssr ([30e92a1](https://github.com/vitejs/vite/commit/30e92a150e060e8bedcb6f0c477dcaa87e7996d6)), closes [#1939](https://github.com/vitejs/vite/issues/1939)
## [1.0.2](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.1...plugin-vue-jsx@1.0.2) (2021-01-12)
### Bug Fixes
* **plugin-vue-jsx:** files should include `index.d.ts` ([#1473](https://github.com/vitejs/vite/issues/1473)) [skip ci] ([f3ab497](https://github.com/vitejs/vite/commit/f3ab497b762e267721ace628bc6c7c5695b0d431))
* **plugin-vue-jsx:** fix define call check ([#1480](https://github.com/vitejs/vite/issues/1480)) ([4ea065f](https://github.com/vitejs/vite/commit/4ea065f6278f30c022ed291bfb0412a674b18dd4))
* **plugin-vue-jsx:** fix vue jsx hmr ([#1495](https://github.com/vitejs/vite/issues/1495)) ([6bdc3eb](https://github.com/vitejs/vite/commit/6bdc3eb2d004a28d2934946e33602f832b1ad8f2))
### Performance Improvements
* **plugin-vue-jsx:** only gen source map when necessary ([bfa8530](https://github.com/vitejs/vite/commit/bfa8530fc60deada634c38cfd6a23ab8ca05d47c))
## [1.0.1](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.0...plugin-vue-jsx@1.0.1) (2021-01-04)
### Bug Fixes
* still let esbuild handle ts ([5903554](https://github.com/vitejs/vite/commit/59035546db7ff4b7020242ba994a5395aac92802))
# 2.0.0-beta.4 (2021-01-04)
# 1.0.0 (2021-01-04)
### Features
* vue-jsx support ([e756c48](https://github.com/vitejs/vite/commit/e756c48ed4c7372d4c8e26016ba4b91880e7e248))
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# @vitejs/plugin-vue-jsx [![npm](https://img.shields.io/npm/v/@vitejs/plugin-vue-jsx.svg)](https://npmjs.com/package/@vitejs/plugin-vue-jsx)
Provides Vue 3 JSX & TSX support with HMR.
```js
// vite.config.js
import vueJsx from '@vitejs/plugin-vue-jsx'
export default {
plugins: [
vueJsx({
// options are passed on to @vue/babel-plugin-jsx
})
]
}
```
## Options
See [@vue/babel-plugin-jsx](https://github.com/vuejs/jsx-next).
## HMR Detection
This plugin supports HMR of Vue JSX components. The detection requirements are:
- The component must be exported.
- The component must be declared by calling `defineComponent` via a root-level statement, either variable declaration or export declaration.
### Supported patterns
```jsx
import { defineComponent } from 'vue'
// named exports w/ variable declaration: ok
export const Foo = defineComponent({})
// named exports referencing variable declaration: ok
const Bar = defineComponent({ render() { return <div>Test</div> }})
export { Bar }
// default export call: ok
export default defineComponent({ render() { return <div>Test</div> }})
// default export referencing variable declaration: ok
const Baz = defineComponent({ render() { return <div>Test</div> }})
export default Baz
```
### Non-supported patterns
```jsx
// not using `defineComponent` call
export const Bar = { ... }
// not exported
const Foo = defineComponent(...)
```
import { Plugin } from 'vite'
import { VueJSXPluginOptions } from '@vue/babel-plugin-jsx'
import { FilterPattern } from '@rollup/pluginutils'
declare interface FilterOptions {
include?: FilterPattern
exclude?: FilterPattern
}
declare function createPlugin(
options?: VueJSXPluginOptions & FilterOptions & { babelPlugins?: any[] }
): Plugin
export default createPlugin
// @ts-check
const babel = require('@babel/core')
const jsx = require('@vue/babel-plugin-jsx')
const importMeta = require('@babel/plugin-syntax-import-meta')
const { createFilter, normalizePath } = require('@rollup/pluginutils')
const hash = require('hash-sum')
const path = require('path')
const ssrRegisterHelperId = '/__vue-jsx-ssr-register-helper'
const ssrRegisterHelperCode =
`import { useSSRContext } from "vue"\n` +
`export ${ssrRegisterHelper.toString()}`
/**
* This function is serialized with toString() and evaluated as a virtual
* module during SSR
* @param {import('vue').ComponentOptions} comp
* @param {string} filename
*/
function ssrRegisterHelper(comp, filename) {
const setup = comp.setup
comp.setup = (props, ctx) => {
// @ts-ignore
const ssrContext = useSSRContext()
;(ssrContext.modules || (ssrContext.modules = new Set())).add(filename)
if (setup) {
return setup(props, ctx)
}
}
}
/**
* @typedef { import('@rollup/pluginutils').FilterPattern} FilterPattern
* @typedef { { include?: FilterPattern, exclude?: FilterPattern, babelPlugins?: any[] } } CommonOptions
*/
/**
*
* @param {import('@vue/babel-plugin-jsx').VueJSXPluginOptions & CommonOptions} options
* @returns {import('vite').Plugin}
*/
function vueJsxPlugin(options = {}) {
let root = ''
let needHmr = false
let needSourceMap = true
return {
name: 'vite:vue-jsx',
config(config) {
return {
// only apply esbuild to ts files
// since we are handling jsx and tsx now
esbuild: {
include: /\.ts$/
},
define: {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false,
...config.define
}
}
},
configResolved(config) {
needHmr = config.command === 'serve' && !config.isProduction
needSourceMap = config.command === 'serve' || !!config.build.sourcemap
root = config.root
},
resolveId(id) {
if (id === ssrRegisterHelperId) {
return id
}
},
load(id) {
if (id === ssrRegisterHelperId) {
return ssrRegisterHelperCode
}
},
transform(code, id, ssr) {
const {
include,
exclude,
babelPlugins = [],
...babelPluginOptions
} = options
// fixed by xxxxxx
const filter = createFilter(include || /\.[jt]sx/, exclude)
if (filter(id)) {
const plugins = [importMeta, [jsx, babelPluginOptions], ...babelPlugins]
// fixed by xxxxxx
if (id.includes('.tsx')) {
plugins.push([
require('@babel/plugin-transform-typescript'),
// @ts-ignore
{ isTSX: true, allowExtensions: true }
])
}
const result = babel.transformSync(code, {
babelrc: false,
ast: true,
plugins,
sourceMaps: needSourceMap,
sourceFileName: id,
configFile: false
})
if (!ssr && !needHmr) {
return {
code: result.code,
map: result.map
}
}
// check for hmr injection
/**
* @type {{ name: string }[]}
*/
const declaredComponents = []
/**
* @type {{
* local: string,
* exported: string,
* id: string,
* }[]}
*/
const hotComponents = []
let hasDefault = false
for (const node of result.ast.program.body) {
if (node.type === 'VariableDeclaration') {
const names = parseComponentDecls(node, code)
if (names.length) {
declaredComponents.push(...names)
}
}
if (node.type === 'ExportNamedDeclaration') {
if (
node.declaration &&
node.declaration.type === 'VariableDeclaration'
) {
hotComponents.push(
...parseComponentDecls(node.declaration, code).map(
({ name }) => ({
local: name,
exported: name,
id: hash(id + name)
})
)
)
} else if (node.specifiers.length) {
for (const spec of node.specifiers) {
if (
spec.type === 'ExportSpecifier' &&
spec.exported.type === 'Identifier'
) {
const matched = declaredComponents.find(
({ name }) => name === spec.local.name
)
if (matched) {
hotComponents.push({
local: spec.local.name,
exported: spec.exported.name,
id: hash(id + spec.exported.name)
})
}
}
}
}
}
if (node.type === 'ExportDefaultDeclaration') {
if (node.declaration.type === 'Identifier') {
const _name = node.declaration.name
const matched = declaredComponents.find(
({ name }) => name === _name
)
if (matched) {
hotComponents.push({
local: node.declaration.name,
exported: 'default',
id: hash(id + 'default')
})
}
} else if (isDefineComponentCall(node.declaration)) {
hasDefault = true
hotComponents.push({
local: '__default__',
exported: 'default',
id: hash(id + 'default')
})
}
}
}
if (hotComponents.length) {
if (hasDefault && (needHmr || ssr)) {
result.code =
result.code.replace(
/export default defineComponent/g,
`const __default__ = defineComponent`
) + `\nexport default __default__`
}
if (needHmr && !ssr && !/\?vue&type=script/.test(id)) {
let code = result.code
let callbackCode = ``
for (const { local, exported, id } of hotComponents) {
code +=
`\n${local}.__hmrId = "${id}"` +
`\n__VUE_HMR_RUNTIME__.createRecord("${id}", ${local})`
callbackCode += `\n__VUE_HMR_RUNTIME__.reload("${id}", __${exported})`
}
code += `\nimport.meta.hot.accept(({${hotComponents
.map((c) => `${c.exported}: __${c.exported}`)
.join(',')}}) => {${callbackCode}\n})`
result.code = code
}
if (ssr) {
const normalizedId = normalizePath(path.relative(root, id))
let ssrInjectCode =
`\nimport { ssrRegisterHelper } from "${ssrRegisterHelperId}"` +
`\nconst __moduleId = ${JSON.stringify(normalizedId)}`
for (const { local } of hotComponents) {
ssrInjectCode += `\nssrRegisterHelper(${local}, __moduleId)`
}
result.code += ssrInjectCode
}
}
return {
code: result.code,
map: result.map
}
}
}
}
}
/**
* @param {import('@babel/core').types.VariableDeclaration} node
* @param {string} source
*/
function parseComponentDecls(node, source) {
const names = []
for (const decl of node.declarations) {
if (decl.id.type === 'Identifier' && isDefineComponentCall(decl.init)) {
names.push({
name: decl.id.name
})
}
}
return names
}
/**
* @param {import('@babel/core').types.Node} node
*/
function isDefineComponentCall(node) {
return (
node &&
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'defineComponent'
)
}
module.exports = vueJsxPlugin
vueJsxPlugin.default = vueJsxPlugin
{
"name": "@vitejs/plugin-vue-jsx",
"version": "1.1.8",
"license": "MIT",
"author": "Evan You",
"files": [
"index.js",
"index.d.ts"
],
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . --lerna-package plugin-vue-jsx",
"release": "node ../../scripts/release.js --skipBuild"
},
"engines": {
"node": ">=12.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vitejs/vite.git",
"directory": "packages/plugin-vue-jsx"
},
"bugs": {
"url": "https://github.com/vitejs/vite/issues"
},
"homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-vue-jsx#readme",
"dependencies": {
"@babel/core": "^7.15.5",
"@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/plugin-transform-typescript": "^7.15.4",
"@rollup/pluginutils": "^4.1.1",
"@vue/babel-plugin-jsx": "^1.0.7",
"hash-sum": "^2.0.0"
}
}
......@@ -9,7 +9,8 @@
"types": "dist/index.d.ts",
"files": [
"dist/**/*.js",
"dist/**/*.d.ts"
"dist/**/*.d.ts",
"lib"
],
"repository": {
"type": "git",
......
......@@ -4,7 +4,6 @@ import { Options as VueOptions } from '@vitejs/plugin-vue'
import { Options as ViteLegacyOptions } from '@vitejs/plugin-legacy'
import { VueJSXPluginOptions } from '@vue/babel-plugin-jsx'
import vuePlugin from '@vitejs/plugin-vue'
import type VueJsxPlugin from '@vitejs/plugin-vue-jsx'
import type ViteLegacyPlugin from '@vitejs/plugin-legacy'
import {
......@@ -37,7 +36,7 @@ export interface VitePluginUniOptions {
inputDir?: string
outputDir?: string
vueOptions?: VueOptions
vueJsxOptions?: VueJSXPluginOptions
vueJsxOptions?: VueJSXPluginOptions | boolean
viteLegacyOptions?: ViteLegacyOptions
}
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
......@@ -53,11 +52,6 @@ export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
export { runDev, runBuild } from './cli/action'
let createVueJsxPlugin: typeof VueJsxPlugin | undefined
try {
createVueJsxPlugin = require('@vitejs/plugin-vue-jsx')
} catch (e) {}
let createViteLegacyPlugin: typeof ViteLegacyPlugin | undefined
try {
createViteLegacyPlugin = require('@vitejs/plugin-legacy')
......@@ -91,8 +85,10 @@ export default function uniPlugin(
)
}
if (createVueJsxPlugin && options.vueJsxOptions !== false) {
plugins.push(createVueJsxPlugin(initPluginVueJsxOptions(options)))
if (options.vueJsxOptions) {
plugins.push(
require('../lib/plugin-vue-jsx/index')(initPluginVueJsxOptions(options))
)
}
const uniPlugins = initExtraPlugins(
......
import { extend, hasOwn, isArray } from '@vue/shared'
import { extend, hasOwn, isArray, isPlainObject } from '@vue/shared'
import { SFCTemplateCompileOptions } from '@vue/compiler-sfc'
import { isCustomElement } from '@dcloudio/uni-shared'
import {
......@@ -114,7 +114,9 @@ export function initPluginVueOptions(
}
export function initPluginVueJsxOptions(options: VitePluginUniResolvedOptions) {
const vueJsxOptions = options.vueJsxOptions || (options.vueJsxOptions = {})
const vueJsxOptions = isPlainObject(options.vueJsxOptions)
? options.vueJsxOptions
: (options.vueJsxOptions = {})
if (!hasOwn(vueJsxOptions, 'optimize')) {
vueJsxOptions.optimize = true
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册