Skip to content

Commit

Permalink
feat: vue-jsx support
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jan 4, 2021
1 parent a55eebc commit 3a2eb55
Show file tree
Hide file tree
Showing 5 changed files with 290 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/plugin-vue-jsx/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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.
14 changes: 14 additions & 0 deletions packages/plugin-vue-jsx/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# @vitejs/plugin-vue-jsx

Provides optimized Vue 3 JSX support via [@vue/babel-plugin-jsx](https://github.com/vuejs/jsx-next).

```js
// vite.config.js
import vueJsx from '@vitejs/plugin-vue-jsx'

export default {
plugins: [vueJsx({
// options are passed on to @vue/babel-plugin-jsx
})]
}
```
13 changes: 13 additions & 0 deletions packages/plugin-vue-jsx/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Plugin } from 'vite'

// https://github.com/vuejs/jsx-next/tree/dev/packages/babel-plugin-jsx#options
export interface Options {
transformOn?: boolean
optimize?: boolean
isCustomElement?: (tag: string) => boolean
mergeProps?: boolean
}

declare function createPlugin(options?: Options): Plugin

export default createPlugin
209 changes: 209 additions & 0 deletions packages/plugin-vue-jsx/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// @ts-check
const babel = require('@babel/core')
const jsx = require('@vue/babel-plugin-jsx')
const importMeta = require('@babel/plugin-syntax-import-meta')
const hash = require('hash-sum')

/**
* @param {import('.').Options} options
* @returns {import('vite').Plugin}
*/
module.exports = function vueJsxPlugin(options = {}) {
let needHmr = false

return {
name: 'vue-jsx',

config(config) {
return {
esbuild: false,
define: {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false,
...config.define
}
}
},

configResolved(config) {
needHmr = config.command === 'serve' && !config.isProduction
},

transform(code, id) {
if (/\.[jt]sx$/.test(id)) {
const plugins = [importMeta, [jsx, options]]
if (id.endsWith('.tsx')) {
plugins.push([
require('@babel/plugin-transform-typescript'),
// @ts-ignore
{ isTSX: true, allowExtensions: true }
])
}

const result = babel.transformSync(code, {
ast: true,
plugins,
sourceMaps: true,
sourceFileName: id
})

if (!needHmr) {
return {
code: result.code,
map: result.map
}
}

// check for hmr injection
/**
* @type {{ name: string, hash: string }[]}
*/
const declaredComponents = []
/**
* @type {{
* local: string,
* exported: string,
* id: string,
* hash: 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, hash: _hash }) => ({
local: name,
exported: name,
id: hash(id + name),
hash: _hash
})
)
)
} 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),
hash: matched.hash
})
}
}
}
}
}

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'),
hash: matched.hash
})
}
} else if (isDefineComponentCall(node.declaration)) {
hasDefault = true
hotComponents.push({
local: '__default__',
exported: 'default',
id: hash(id + 'default'),
hash: hash(
code.slice(node.declaration.start, node.declaration.end)
)
})
}
}
}

if (hotComponents.length) {
let code = result.code
if (hasDefault) {
code =
code.replace(
/export default defineComponent/g,
`const __default__ = defineComponent`
) + `\nexport default __default__`
}

let callbackCode = ``
for (const { local, exported, id, hash } of hotComponents) {
code +=
`\n${local}.__hmrId = "${id}"` +
`\n${local}.__hmrHash = "${hash}"` +
`\n__VUE_HMR_RUNTIME__.createRecord("${id}", ${local})`
callbackCode +=
`\n if (__${exported}.__hmrHash !== ${local}.__hmrHash) ` +
`__VUE_HMR_RUNTIME__.reload("${id}", __${exported})`
}

code += `\nimport.meta.hot.accept(({${hotComponents
.map((c) => `${c.exported}: __${c.exported}`)
.join(',')}}) => {${callbackCode}\n})`

result.code = code
}

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,
hash: hash(source.slice(decl.init.start, decl.init.end))
})
}
}
return names
}

/**
* @param {import('@babel/core').types.Node} node
*/
function isDefineComponentCall(node) {
return (
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'defineComponent'
)
}
33 changes: 33 additions & 0 deletions packages/plugin-vue-jsx/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@vitejs/plugin-vue-jsx",
"version": "1.0.0",
"license": "MIT",
"author": "Evan You",
"files": [
"index.js"
],
"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"
},
"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.12.10",
"@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/plugin-transform-typescript": "^7.12.1",
"@vue/babel-plugin-jsx": "^1.0.0",
"hash-sum": "^2.0.0"
}
}

0 comments on commit 3a2eb55

Please sign in to comment.