mirror of
https://github.com/vuejs/babel-plugin-jsx.git
synced 2025-07-19 22:19:57 +08:00
refactor: with TypeScript (#24)
* refactor: add ts support (#19) Co-authored-by: 逆寒 <869732751@qq.com>
This commit is contained in:
2
packages/babel-plugin-jsx/global.d.ts
vendored
Normal file
2
packages/babel-plugin-jsx/global.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
declare module '@babel/helper-module-imports';
|
||||
declare module '@babel/plugin-syntax-jsx';
|
@ -12,9 +12,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "npm run build && webpack-dev-server",
|
||||
"build": "rollup -c",
|
||||
"build": "tsc",
|
||||
"lint": "eslint --ext .js src",
|
||||
"test": "jest --coverage"
|
||||
"test": "npm run build && jest --coverage"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vueComponent/jsx/issues"
|
||||
@ -27,13 +27,14 @@
|
||||
"@ant-design-vue/babel-helper-vue-transform-on": "^1.0.0",
|
||||
"@babel/helper-module-imports": "^7.0.0",
|
||||
"@babel/plugin-syntax-jsx": "^7.0.0",
|
||||
"@babel/types": "^7.0.0",
|
||||
"camelcase": "^6.0.0",
|
||||
"html-tags": "^3.1.0",
|
||||
"svg-tags": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.9.6",
|
||||
"@babel/preset-env": "^7.9.6",
|
||||
"@babel/core": "^7.0.0",
|
||||
"@babel/preset-env": "^7.0.0",
|
||||
"@rollup/plugin-babel": "^5.0.3",
|
||||
"@vue/compiler-dom": "3.0.0-beta.20",
|
||||
"@vue/test-utils": "^2.0.0-alpha.8",
|
||||
@ -43,6 +44,7 @@
|
||||
"regenerator-runtime": "^0.13.5",
|
||||
"rollup": "^2.13.1",
|
||||
"vue": "3.0.0-beta.20",
|
||||
"typescript": "^3.9.6",
|
||||
"webpack": "^4.43.0",
|
||||
"webpack-cli": "^3.3.11",
|
||||
"webpack-dev-server": "^3.10.3"
|
||||
|
@ -1,22 +1,12 @@
|
||||
import babel from '@rollup/plugin-babel';
|
||||
// import babel from '@rollup/plugin-babel';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
|
||||
export default {
|
||||
input: 'src/index.js',
|
||||
input: 'src/index.ts',
|
||||
plugins: [
|
||||
babel({
|
||||
presets: [
|
||||
[
|
||||
'@babel/preset-env',
|
||||
{
|
||||
targets: {
|
||||
node: 8,
|
||||
},
|
||||
modules: false,
|
||||
},
|
||||
],
|
||||
],
|
||||
configFile: false,
|
||||
}),
|
||||
commonjs(),
|
||||
typescript(),
|
||||
],
|
||||
output: [
|
||||
{
|
||||
|
@ -1,12 +0,0 @@
|
||||
import syntaxJsx from '@babel/plugin-syntax-jsx';
|
||||
import tranformVueJSX from './transform-vue-jsx';
|
||||
import sugarFragment from './sugar-fragment';
|
||||
|
||||
export default ({ types: t }) => ({
|
||||
name: 'babel-plugin-jsx',
|
||||
inherits: syntaxJsx,
|
||||
visitor: {
|
||||
...tranformVueJSX(t),
|
||||
...sugarFragment(t),
|
||||
},
|
||||
});
|
25
packages/babel-plugin-jsx/src/index.ts
Normal file
25
packages/babel-plugin-jsx/src/index.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import syntaxJsx from '@babel/plugin-syntax-jsx';
|
||||
import tranformVueJSX from './transform-vue-jsx';
|
||||
import sugarFragment from './sugar-fragment';
|
||||
|
||||
export type State = {
|
||||
get: (name: string) => any;
|
||||
set: (name: string, value: any) => any;
|
||||
opts: Opts;
|
||||
}
|
||||
|
||||
interface Opts {
|
||||
transformOn?: boolean;
|
||||
compatibleProps?: boolean;
|
||||
}
|
||||
|
||||
export type ExcludesFalse = <T>(x: T | false) => x is T;
|
||||
|
||||
export default () => ({
|
||||
name: 'babel-plugin-jsx',
|
||||
inherits: syntaxJsx,
|
||||
visitor: {
|
||||
...tranformVueJSX(),
|
||||
...sugarFragment(),
|
||||
},
|
||||
});
|
33
packages/babel-plugin-jsx/src/patchFlags.ts
Normal file
33
packages/babel-plugin-jsx/src/patchFlags.ts
Normal file
@ -0,0 +1,33 @@
|
||||
// https://github.com/vuejs/vue-next/blob/master/packages/shared/src/patchFlags.ts
|
||||
export const enum PatchFlags {
|
||||
TEXT = 1,
|
||||
CLASS = 1 << 1,
|
||||
STYLE = 1 << 2,
|
||||
PROPS = 1 << 3,
|
||||
FULL_PROPS = 1 << 4,
|
||||
HYDRATE_EVENTS = 1 << 5,
|
||||
STABLE_FRAGMENT = 1 << 6,
|
||||
KEYED_FRAGMENT = 1 << 7,
|
||||
UNKEYED_FRAGMENT = 1 << 8,
|
||||
NEED_PATCH = 1 << 9,
|
||||
DYNAMIC_SLOTS = 1 << 10,
|
||||
HOISTED = -1,
|
||||
BAIL = -2
|
||||
}
|
||||
|
||||
// dev only flag -> name mapping
|
||||
export const PatchFlagNames = {
|
||||
[PatchFlags.TEXT]: `TEXT`,
|
||||
[PatchFlags.CLASS]: `CLASS`,
|
||||
[PatchFlags.STYLE]: `STYLE`,
|
||||
[PatchFlags.PROPS]: `PROPS`,
|
||||
[PatchFlags.FULL_PROPS]: `FULL_PROPS`,
|
||||
[PatchFlags.HYDRATE_EVENTS]: `HYDRATE_EVENTS`,
|
||||
[PatchFlags.STABLE_FRAGMENT]: `STABLE_FRAGMENT`,
|
||||
[PatchFlags.KEYED_FRAGMENT]: `KEYED_FRAGMENT`,
|
||||
[PatchFlags.UNKEYED_FRAGMENT]: `UNKEYED_FRAGMENT`,
|
||||
[PatchFlags.DYNAMIC_SLOTS]: `DYNAMIC_SLOTS`,
|
||||
[PatchFlags.NEED_PATCH]: `NEED_PATCH`,
|
||||
[PatchFlags.HOISTED]: `HOISTED`,
|
||||
[PatchFlags.BAIL]: `BAIL`
|
||||
}
|
@ -1,6 +1,9 @@
|
||||
import * as t from '@babel/types'
|
||||
import { addNamespace } from '@babel/helper-module-imports';
|
||||
import { NodePath } from '@babel/traverse';
|
||||
import { State } from './';
|
||||
|
||||
const transformFragment = (t, path, Fragment) => {
|
||||
const transformFragment = (path: NodePath<t.JSXElement>, Fragment: t.JSXMemberExpression) => {
|
||||
const children = path.get('children') || [];
|
||||
return t.jsxElement(
|
||||
t.jsxOpeningElement(Fragment, []),
|
||||
@ -10,15 +13,15 @@ const transformFragment = (t, path, Fragment) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default (t) => ({
|
||||
export default () => ({
|
||||
JSXFragment: {
|
||||
enter(path, state) {
|
||||
enter(path: NodePath<t.JSXElement>, state: State) {
|
||||
if (!state.get('vue')) {
|
||||
state.set('vue', addNamespace(path, 'vue'));
|
||||
}
|
||||
path.replaceWith(
|
||||
transformFragment(
|
||||
t, path,
|
||||
path,
|
||||
t.jsxMemberExpression(
|
||||
t.jsxIdentifier(state.get('vue').name),
|
||||
t.jsxIdentifier('Fragment'),
|
@ -1,39 +1,49 @@
|
||||
import * as t from '@babel/types';
|
||||
import { NodePath } from '@babel/traverse';
|
||||
import { addDefault, addNamespace } from '@babel/helper-module-imports';
|
||||
import {
|
||||
createIdentifier,
|
||||
PatchFlags,
|
||||
PatchFlagNames,
|
||||
isDirective,
|
||||
checkIsComponent,
|
||||
transformJSXSpreadChild,
|
||||
getTag,
|
||||
getJSXAttributeName,
|
||||
transformJSXText,
|
||||
transformJSXExpressionContainer,
|
||||
transformJSXSpreadChild,
|
||||
parseDirectives,
|
||||
isFragment,
|
||||
} from './utils';
|
||||
import { PatchFlags, PatchFlagNames } from './patchFlags';
|
||||
import { State, ExcludesFalse } from './';
|
||||
|
||||
const xlinkRE = /^xlink([A-Z])/;
|
||||
const onRE = /^on[^a-z]/;
|
||||
|
||||
const isOn = (key) => onRE.test(key);
|
||||
const isOn = (key: string) => onRE.test(key);
|
||||
|
||||
const transformJSXSpreadAttribute = (t, path, mergeArgs) => {
|
||||
const argument = path.get('argument').node;
|
||||
const { properties } = argument;
|
||||
const transformJSXSpreadAttribute = (
|
||||
path: NodePath<t.JSXSpreadAttribute>,
|
||||
mergeArgs: (t.ObjectProperty | t.Expression)[]
|
||||
) => {
|
||||
const argument = path.get('argument') as NodePath<t.ObjectExpression>;
|
||||
const { properties } = argument.node;
|
||||
if (!properties) {
|
||||
// argument is an Identifier
|
||||
mergeArgs.push(argument);
|
||||
mergeArgs.push(argument.node);
|
||||
} else {
|
||||
mergeArgs.push(t.objectExpression(properties));
|
||||
}
|
||||
};
|
||||
|
||||
const getJSXAttributeValue = (t, path, state) => {
|
||||
const getJSXAttributeValue = (
|
||||
path: NodePath<t.JSXAttribute>,
|
||||
state: State
|
||||
): (
|
||||
t.StringLiteral | t.Expression | null
|
||||
) => {
|
||||
const valuePath = path.get('value');
|
||||
if (valuePath.isJSXElement()) {
|
||||
return transformJSXElement(t, valuePath, state);
|
||||
return transformJSXElement(valuePath, state);
|
||||
}
|
||||
if (valuePath.isStringLiteral()) {
|
||||
return valuePath.node;
|
||||
@ -47,46 +57,48 @@ const getJSXAttributeValue = (t, path, state) => {
|
||||
|
||||
/**
|
||||
* Check if an attribute value is constant
|
||||
* @param t
|
||||
* @param path
|
||||
* @returns boolean
|
||||
*/
|
||||
const isConstant = (t, path) => {
|
||||
if (t.isIdentifier(path)) {
|
||||
return path.name === 'undefined';
|
||||
const isConstant = (
|
||||
node: t.Expression | t.Identifier | t.Literal | t.SpreadElement | null
|
||||
): boolean => {
|
||||
if (t.isIdentifier(node)) {
|
||||
return node.name === 'undefined';
|
||||
}
|
||||
if (t.isArrayExpression(path)) {
|
||||
return path.elements.every((element) => isConstant(t, element));
|
||||
if (t.isArrayExpression(node)) {
|
||||
const elements = node.elements;
|
||||
return elements.every((element) => element && isConstant(element));
|
||||
}
|
||||
if (t.isObjectExpression(path)) {
|
||||
return path.properties.every((property) => isConstant(t, property.value));
|
||||
if (t.isObjectExpression(node)) {
|
||||
return node.properties.every((property) => isConstant((property as any).value));
|
||||
}
|
||||
if (t.isLiteral(path)) {
|
||||
if (t.isLiteral(node)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const mergeAsArray = (t, existing, incoming) => {
|
||||
const mergeAsArray = (existing: t.ObjectProperty, incoming: t.ObjectProperty) => {
|
||||
if (t.isArrayExpression(existing.value)) {
|
||||
existing.value.elements.push(incoming.value);
|
||||
existing.value.elements.push(incoming.value as t.Expression);
|
||||
} else {
|
||||
existing.value = t.arrayExpression([
|
||||
existing.value,
|
||||
incoming.value,
|
||||
existing.value as t.Expression,
|
||||
incoming.value as t.Expression,
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
const dedupeProperties = (t, properties = []) => {
|
||||
const knownProps = new Map();
|
||||
const deduped = [];
|
||||
const dedupeProperties = (properties: t.ObjectProperty[] = []) => {
|
||||
const knownProps = new Map<string, t.ObjectProperty>();
|
||||
const deduped: t.ObjectProperty[] = [];
|
||||
properties.forEach((prop) => {
|
||||
const { key: { value: name } = {} } = prop;
|
||||
const { value: name } = prop.key as t.StringLiteral;
|
||||
const existing = knownProps.get(name);
|
||||
if (existing) {
|
||||
if (name === 'style' || name === 'class' || name.startsWith('on')) {
|
||||
mergeAsArray(t, existing, prop);
|
||||
mergeAsArray(existing, prop);
|
||||
}
|
||||
} else {
|
||||
knownProps.set(name, prop);
|
||||
@ -97,19 +109,17 @@ const dedupeProperties = (t, properties = []) => {
|
||||
return deduped;
|
||||
};
|
||||
|
||||
const buildProps = (t, path, state, hasContainer) => {
|
||||
const tag = getTag(t, path);
|
||||
const isComponent = checkIsComponent(t, path.get('openingElement'));
|
||||
const buildProps = (path: NodePath<t.JSXElement>, state: State) => {
|
||||
const tag = getTag(path, state);
|
||||
const isComponent = checkIsComponent(path.get('openingElement'));
|
||||
const props = path.get('openingElement').get('attributes');
|
||||
const directives = [];
|
||||
const directives: t.ArrayExpression[] = [];
|
||||
const dynamicPropNames = new Set();
|
||||
|
||||
let patchFlag = 0;
|
||||
|
||||
if (isFragment(t, path.get('openingElement.name'))) {
|
||||
if (isFragment(path.get('openingElement').get('name'))) {
|
||||
patchFlag |= PatchFlags.STABLE_FRAGMENT;
|
||||
} else if (hasContainer) {
|
||||
patchFlag |= PatchFlags.BAIL;
|
||||
}
|
||||
|
||||
if (props.length === 0) {
|
||||
@ -122,7 +132,7 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
};
|
||||
}
|
||||
|
||||
const properties = [];
|
||||
const properties: t.ObjectProperty[] = [];
|
||||
|
||||
// patchFlag analysis
|
||||
let hasRef = false;
|
||||
@ -131,16 +141,15 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
let hasHydrationEventBinding = false;
|
||||
let hasDynamicKeys = false;
|
||||
|
||||
const mergeArgs = [];
|
||||
|
||||
const mergeArgs: (t.CallExpression | t.ObjectProperty | t.Identifier)[] = [];
|
||||
props
|
||||
.forEach((prop) => {
|
||||
if (prop.isJSXAttribute()) {
|
||||
let name = getJSXAttributeName(t, prop);
|
||||
let name = getJSXAttributeName(prop);
|
||||
|
||||
const attributeValue = getJSXAttributeValue(t, prop);
|
||||
const attributeValue = getJSXAttributeValue(prop, state);
|
||||
|
||||
if (!isConstant(t, attributeValue) || name === 'ref') {
|
||||
if (!isConstant(attributeValue) || name === 'ref') {
|
||||
if (
|
||||
!isComponent
|
||||
&& isOn(name)
|
||||
@ -182,16 +191,14 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
return;
|
||||
}
|
||||
if (isDirective(name)) {
|
||||
const { directive, modifiers, directiveName } = parseDirectives(
|
||||
t, {
|
||||
tag,
|
||||
isComponent,
|
||||
name,
|
||||
path: prop,
|
||||
state,
|
||||
value: attributeValue,
|
||||
},
|
||||
);
|
||||
const { directive, modifiers, directiveName } = parseDirectives({
|
||||
tag,
|
||||
isComponent,
|
||||
name,
|
||||
path: prop,
|
||||
state,
|
||||
value: attributeValue,
|
||||
});
|
||||
|
||||
if (directive) {
|
||||
directives.push(t.arrayExpression(directive));
|
||||
@ -199,6 +206,7 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
// must be v-model and is a component
|
||||
properties.push(t.objectProperty(
|
||||
t.stringLiteral('modelValue'),
|
||||
// @ts-ignore
|
||||
attributeValue,
|
||||
));
|
||||
|
||||
@ -219,11 +227,12 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (directiveName === 'model') {
|
||||
if (directiveName === 'model' && attributeValue) {
|
||||
properties.push(t.objectProperty(
|
||||
t.stringLiteral('onUpdate:modelValue'),
|
||||
t.arrowFunctionExpression(
|
||||
[t.identifier('$event')],
|
||||
// @ts-ignore
|
||||
t.assignmentExpression('=', attributeValue, t.identifier('$event')),
|
||||
),
|
||||
));
|
||||
@ -240,8 +249,9 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
attributeValue || t.booleanLiteral(true),
|
||||
));
|
||||
} else {
|
||||
// JSXSpreadAttribute
|
||||
hasDynamicKeys = true;
|
||||
transformJSXSpreadAttribute(t, prop, mergeArgs);
|
||||
transformJSXSpreadAttribute(prop as NodePath<t.JSXSpreadAttribute>, mergeArgs);
|
||||
}
|
||||
});
|
||||
|
||||
@ -270,15 +280,15 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
patchFlag |= PatchFlags.NEED_PATCH;
|
||||
}
|
||||
|
||||
let propsExpression = t.nullLiteral();
|
||||
let propsExpression: t.Expression | t.ObjectProperty | t.Literal = t.nullLiteral();
|
||||
|
||||
if (mergeArgs.length) {
|
||||
if (properties.length) {
|
||||
mergeArgs.push(...dedupeProperties(t, properties));
|
||||
mergeArgs.push(...dedupeProperties(properties));
|
||||
}
|
||||
if (mergeArgs.length > 1) {
|
||||
const exps = [];
|
||||
const objectProperties = [];
|
||||
const exps: (t.CallExpression | t.Identifier)[] = [];
|
||||
const objectProperties: t.ObjectProperty[] = [];
|
||||
mergeArgs.forEach((arg) => {
|
||||
if (t.isIdentifier(arg) || t.isExpression(arg)) {
|
||||
exps.push(arg);
|
||||
@ -287,20 +297,18 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
}
|
||||
});
|
||||
propsExpression = t.callExpression(
|
||||
createIdentifier(t, state, 'mergeProps'),
|
||||
createIdentifier(state, 'mergeProps'),
|
||||
[
|
||||
...exps,
|
||||
objectProperties.length
|
||||
&& t.objectExpression(objectProperties),
|
||||
].filter(Boolean),
|
||||
!!objectProperties.length && t.objectExpression(objectProperties),
|
||||
].filter(Boolean as any as ExcludesFalse),
|
||||
);
|
||||
} else {
|
||||
// single no need for a mergeProps call
|
||||
// eslint-disable-next-line prefer-destructuring
|
||||
propsExpression = mergeArgs[0];
|
||||
}
|
||||
} else if (properties.length) {
|
||||
propsExpression = t.objectExpression(dedupeProperties(t, properties));
|
||||
propsExpression = t.objectExpression(dedupeProperties(properties));
|
||||
}
|
||||
|
||||
return {
|
||||
@ -314,50 +322,59 @@ const buildProps = (t, path, state, hasContainer) => {
|
||||
|
||||
/**
|
||||
* Get children from Array of JSX children
|
||||
* @param t
|
||||
* @param paths Array<JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement>
|
||||
* @param paths Array<JSXText | JSXExpressionContainer | JSXElement | JSXFragment>
|
||||
* @returns Array<Expression | SpreadElement>
|
||||
*/
|
||||
const getChildren = (t, paths, state) => {
|
||||
let hasContainer = false;
|
||||
return {
|
||||
children: paths
|
||||
.map((path) => {
|
||||
if (path.isJSXText()) {
|
||||
return transformJSXText(t, path);
|
||||
const getChildren = (
|
||||
paths: NodePath<
|
||||
t.JSXText
|
||||
| t.JSXExpressionContainer
|
||||
| t.JSXSpreadChild
|
||||
| t.JSXElement
|
||||
| t.JSXFragment
|
||||
>[],
|
||||
state: State
|
||||
): t.Expression[] =>
|
||||
paths
|
||||
.map((path) => {
|
||||
if (path.isJSXText()) {
|
||||
const transformedText = transformJSXText(path);
|
||||
if (transformedText) {
|
||||
return t.callExpression(createIdentifier(state, 'createTextVNode'), [transformedText]);
|
||||
}
|
||||
if (path.isJSXExpressionContainer()) {
|
||||
hasContainer = true;
|
||||
return transformJSXExpressionContainer(path);
|
||||
}
|
||||
if (path.isJSXSpreadChild()) {
|
||||
return transformJSXSpreadChild(t, path);
|
||||
}
|
||||
if (path.isCallExpression()) {
|
||||
return path.node;
|
||||
}
|
||||
if (path.isJSXElement()) {
|
||||
return transformJSXElement(t, path, state);
|
||||
}
|
||||
throw new Error(`getChildren: ${path.type} is not supported`);
|
||||
}).filter((value) => (
|
||||
value !== undefined
|
||||
return transformedText;
|
||||
}
|
||||
if (path.isJSXExpressionContainer()) {
|
||||
return transformJSXExpressionContainer(path);
|
||||
}
|
||||
if (t.isJSXSpreadChild(path)) {
|
||||
return transformJSXSpreadChild(path as NodePath<t.JSXSpreadChild>);
|
||||
}
|
||||
if (path.isCallExpression()) {
|
||||
return path.node;
|
||||
}
|
||||
if (path.isJSXElement()) {
|
||||
return transformJSXElement(path, state);
|
||||
}
|
||||
throw new Error(`getChildren: ${path.type} is not supported`);
|
||||
}).filter(((value: any) => (
|
||||
value !== undefined
|
||||
&& value !== null
|
||||
&& !t.isJSXEmptyExpression(value)
|
||||
)),
|
||||
hasContainer,
|
||||
};
|
||||
};
|
||||
)) as any);
|
||||
|
||||
const transformJSXElement = (t, path, state) => {
|
||||
const { children, hasContainer } = getChildren(t, path.get('children'), state);
|
||||
const transformJSXElement = (
|
||||
path: NodePath<t.JSXElement>,
|
||||
state: State
|
||||
): t.CallExpression => {
|
||||
const children = getChildren(path.get('children'), state);
|
||||
const {
|
||||
tag,
|
||||
props,
|
||||
directives,
|
||||
patchFlag,
|
||||
dynamicPropNames,
|
||||
} = buildProps(t, path, state, hasContainer);
|
||||
} = buildProps(path, state);
|
||||
|
||||
const flagNames = Object.keys(PatchFlagNames)
|
||||
.map(Number)
|
||||
@ -365,10 +382,6 @@ const transformJSXElement = (t, path, state) => {
|
||||
.map((n) => PatchFlagNames[n])
|
||||
.join(', ');
|
||||
|
||||
const isComponent = checkIsComponent(t, path.get('openingElement'));
|
||||
const child = children.length === 1 && t.isStringLiteral(children[0])
|
||||
? children[0] : t.arrayExpression(children);
|
||||
|
||||
const { compatibleProps } = state.opts;
|
||||
if (compatibleProps && !state.get('compatibleProps')) {
|
||||
state.set('compatibleProps', addDefault(
|
||||
@ -376,53 +389,35 @@ const transformJSXElement = (t, path, state) => {
|
||||
));
|
||||
}
|
||||
|
||||
const createVNode = t.callExpression(createIdentifier(t, state, 'createVNode'), [
|
||||
// @ts-ignore
|
||||
const createVNode = t.callExpression(createIdentifier(state, 'createVNode'), [
|
||||
tag,
|
||||
// @ts-ignore
|
||||
compatibleProps ? t.callExpression(state.get('compatibleProps'), [props]) : props,
|
||||
children[0]
|
||||
? (
|
||||
isComponent
|
||||
? t.objectExpression([
|
||||
t.objectProperty(
|
||||
t.identifier('default'),
|
||||
t.callExpression(createIdentifier(t, state, 'withCtx'), [
|
||||
t.arrowFunctionExpression(
|
||||
[],
|
||||
t.isStringLiteral(child)
|
||||
? t.callExpression(
|
||||
createIdentifier(t, state, 'createTextVNode'),
|
||||
[child],
|
||||
)
|
||||
: child,
|
||||
),
|
||||
]),
|
||||
),
|
||||
])
|
||||
: child
|
||||
) : t.nullLiteral(),
|
||||
patchFlag && t.addComment(t.numericLiteral(patchFlag), 'trailing', ` ${flagNames} `, false),
|
||||
dynamicPropNames.size
|
||||
&& t.arrayExpression([...dynamicPropNames.keys()].map((name) => t.stringLiteral(name))),
|
||||
].filter(Boolean));
|
||||
!!children.length ? t.arrayExpression(children) : t.nullLiteral(),
|
||||
!!patchFlag && t.addComment(t.numericLiteral(patchFlag), 'trailing', ` ${flagNames} `, false),
|
||||
!!dynamicPropNames.size
|
||||
&& t.arrayExpression([...dynamicPropNames.keys()].map((name) => t.stringLiteral(name as string))),
|
||||
].filter(Boolean as any as ExcludesFalse));
|
||||
|
||||
if (!directives.length) {
|
||||
return createVNode;
|
||||
}
|
||||
|
||||
return t.callExpression(createIdentifier(t, state, 'withDirectives'), [
|
||||
return t.callExpression(createIdentifier(state, 'withDirectives'), [
|
||||
createVNode,
|
||||
t.arrayExpression(directives),
|
||||
]);
|
||||
};
|
||||
|
||||
export default (t) => ({
|
||||
export default () => ({
|
||||
JSXElement: {
|
||||
exit(path, state) {
|
||||
exit(path: NodePath<t.JSXElement>, state: State) {
|
||||
if (!state.get('vue')) {
|
||||
state.set('vue', addNamespace(path, 'vue'));
|
||||
}
|
||||
path.replaceWith(
|
||||
transformJSXElement(t, path, state),
|
||||
transformJSXElement(path, state),
|
||||
);
|
||||
},
|
||||
},
|
@ -1,119 +1,97 @@
|
||||
import * as t from '@babel/types';
|
||||
import htmlTags from 'html-tags';
|
||||
import svgTags from 'svg-tags';
|
||||
import { NodePath } from '@babel/traverse';
|
||||
import { State, ExcludesFalse } from './';
|
||||
|
||||
const PatchFlags = {
|
||||
TEXT: 1,
|
||||
CLASS: 1 << 1,
|
||||
STYLE: 1 << 2,
|
||||
PROPS: 1 << 3,
|
||||
FULL_PROPS: 1 << 4,
|
||||
HYDRATE_EVENTS: 1 << 5,
|
||||
STABLE_FRAGMENT: 1 << 6,
|
||||
KEYED_FRAGMENT: 1 << 7,
|
||||
UNKEYED_FRAGMENT: 1 << 8,
|
||||
NEED_PATCH: 1 << 9,
|
||||
DYNAMIC_SLOTS: 1 << 10,
|
||||
HOISTED: -1,
|
||||
BAIL: -2,
|
||||
};
|
||||
|
||||
// dev only flag -> name mapping
|
||||
const PatchFlagNames = {
|
||||
[PatchFlags.TEXT]: 'TEXT',
|
||||
[PatchFlags.CLASS]: 'CLASS',
|
||||
[PatchFlags.STYLE]: 'STYLE',
|
||||
[PatchFlags.PROPS]: 'PROPS',
|
||||
[PatchFlags.FULL_PROPS]: 'FULL_PROPS',
|
||||
[PatchFlags.HYDRATE_EVENTS]: 'HYDRATE_EVENTS',
|
||||
[PatchFlags.STABLE_FRAGMENT]: 'STABLE_FRAGMENT',
|
||||
[PatchFlags.KEYED_FRAGMENT]: 'KEYED_FRAGMENT',
|
||||
[PatchFlags.UNKEYED_FRAGMENT]: 'UNKEYED_FRAGMENT',
|
||||
[PatchFlags.NEED_PATCH]: 'NEED_PATCH',
|
||||
[PatchFlags.DYNAMIC_SLOTS]: 'DYNAMIC_SLOTS',
|
||||
[PatchFlags.HOISTED]: 'HOISTED',
|
||||
[PatchFlags.BAIL]: 'BAIL',
|
||||
};
|
||||
|
||||
const createIdentifier = (t, state, id) => t.memberExpression(state.get('vue'), t.identifier(id));
|
||||
/**
|
||||
* create Identifier
|
||||
* @param state
|
||||
* @param id string
|
||||
* @returns MemberExpression
|
||||
*/
|
||||
const createIdentifier = (
|
||||
state: State, id: string
|
||||
): t.MemberExpression => t.memberExpression(state.get('vue'), t.identifier(id));
|
||||
|
||||
/**
|
||||
* Checks if string is describing a directive
|
||||
* @param src string
|
||||
*/
|
||||
const isDirective = (src) => src.startsWith('v-')
|
||||
const isDirective = (src: string): boolean => src.startsWith('v-')
|
||||
|| (src.startsWith('v') && src.length >= 2 && src[1] >= 'A' && src[1] <= 'Z');
|
||||
|
||||
/**
|
||||
* Check if a JSXOpeningElement is fragment
|
||||
* @param {*} t
|
||||
* @param {*} path
|
||||
* Check if a Node is fragment
|
||||
* @param {*} path JSXIdentifier | JSXMemberExpression | JSXNamespacedName
|
||||
* @returns boolean
|
||||
*/
|
||||
const isFragment = (t, path) => t.isJSXMemberExpression(path)
|
||||
&& path.node.property.name === 'Fragment';
|
||||
const isFragment = (path: NodePath<t.JSXIdentifier | t.JSXMemberExpression | t.JSXNamespacedName>) =>
|
||||
t.isJSXMemberExpression(path)
|
||||
&& (path.node as t.JSXMemberExpression).property.name === 'Fragment';
|
||||
|
||||
/**
|
||||
* Check if a JSXOpeningElement is a component
|
||||
* Check if a Node is a component
|
||||
*
|
||||
* @param t
|
||||
* @param path JSXOpeningElement
|
||||
* @returns boolean
|
||||
*/
|
||||
const checkIsComponent = (t, path) => {
|
||||
const checkIsComponent = (path: NodePath<t.JSXOpeningElement>): boolean => {
|
||||
const namePath = path.get('name');
|
||||
|
||||
if (t.isJSXMemberExpression(namePath)) {
|
||||
return !isFragment(t, namePath); // For withCtx
|
||||
return !isFragment(namePath); // For withCtx
|
||||
}
|
||||
|
||||
const tag = namePath.get('name').node;
|
||||
const tag = (namePath as NodePath<t.JSXIdentifier>).get('name');
|
||||
|
||||
return !htmlTags.includes(tag) && !svgTags.includes(tag);
|
||||
};
|
||||
|
||||
/**
|
||||
* Transform JSXMemberExpression to MemberExpression
|
||||
* @param t
|
||||
* @param path JSXMemberExpression
|
||||
* @returns MemberExpression
|
||||
*/
|
||||
const transformJSXMemberExpression = (t, path) => {
|
||||
const objectPath = path.get('object');
|
||||
const propertyPath = path.get('property');
|
||||
|
||||
const transformedObject = objectPath.isJSXMemberExpression()
|
||||
? transformJSXMemberExpression(t, objectPath)
|
||||
: objectPath.isJSXIdentifier()
|
||||
? t.identifier(objectPath.node.name)
|
||||
const transformJSXMemberExpression = (path: NodePath<t.JSXMemberExpression>): t.MemberExpression => {
|
||||
const objectPath = path.node.object;
|
||||
const propertyPath = path.node.property;
|
||||
const transformedObject = t.isJSXMemberExpression(objectPath)
|
||||
? transformJSXMemberExpression(path.get('object') as NodePath<t.JSXMemberExpression>)
|
||||
: t.isJSXIdentifier(objectPath)
|
||||
? t.identifier(objectPath.name)
|
||||
: t.nullLiteral();
|
||||
const transformedProperty = t.identifier(propertyPath.get('name').node);
|
||||
const transformedProperty = t.identifier(propertyPath.name);
|
||||
return t.memberExpression(transformedObject, transformedProperty);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get tag (first attribute for h) from JSXOpeningElement
|
||||
* @param t
|
||||
* @param path JSXOpeningElement
|
||||
* @param path JSXElement
|
||||
* @param state State
|
||||
* @returns Identifier | StringLiteral | MemberExpression
|
||||
*/
|
||||
const getTag = (t, path) => {
|
||||
const getTag = (path: NodePath<t.JSXElement>, state: State) => {
|
||||
const namePath = path.get('openingElement').get('name');
|
||||
if (namePath.isJSXIdentifier()) {
|
||||
const { name } = namePath.node;
|
||||
if (path.scope.hasBinding(name) && !htmlTags.includes(name) && !svgTags.includes(name)) {
|
||||
return t.identifier(name);
|
||||
if (!htmlTags.includes(name) && !svgTags.includes(name)) {
|
||||
return path.scope.hasBinding(name)
|
||||
? t.identifier(name)
|
||||
: t.callExpression(createIdentifier(state, 'resolveComponent'), [t.stringLiteral(name)]);
|
||||
}
|
||||
|
||||
return t.stringLiteral(name);
|
||||
}
|
||||
|
||||
if (namePath.isJSXMemberExpression()) {
|
||||
return transformJSXMemberExpression(t, namePath);
|
||||
return transformJSXMemberExpression(namePath);
|
||||
}
|
||||
throw new Error(`getTag: ${namePath.type} is not supported`);
|
||||
};
|
||||
|
||||
const getJSXAttributeName = (t, path) => {
|
||||
const getJSXAttributeName = (path: NodePath<t.JSXAttribute>): string => {
|
||||
const nameNode = path.node.name;
|
||||
if (t.isJSXIdentifier(nameNode)) {
|
||||
return nameNode.name;
|
||||
@ -124,11 +102,10 @@ const getJSXAttributeName = (t, path) => {
|
||||
|
||||
/**
|
||||
* Transform JSXText to StringLiteral
|
||||
* @param t
|
||||
* @param path JSXText
|
||||
* @returns StringLiteral
|
||||
* @returns StringLiteral | null
|
||||
*/
|
||||
const transformJSXText = (t, path) => {
|
||||
const transformJSXText = (path: NodePath<t.JSXText>): t.StringLiteral | null => {
|
||||
const { node } = path;
|
||||
const lines = node.value.split(/\r\n|\n|\r/);
|
||||
|
||||
@ -179,64 +156,69 @@ const transformJSXText = (t, path) => {
|
||||
* @param path JSXExpressionContainer
|
||||
* @returns Expression
|
||||
*/
|
||||
const transformJSXExpressionContainer = (path) => path.get('expression').node;
|
||||
const transformJSXExpressionContainer = (
|
||||
path: NodePath<t.JSXExpressionContainer>
|
||||
): (t.Expression) => path.get('expression').node as t.Expression;
|
||||
|
||||
/**
|
||||
* Transform JSXSpreadChild
|
||||
* @param t
|
||||
* @param path JSXSpreadChild
|
||||
* @returns SpreadElement
|
||||
*/
|
||||
const transformJSXSpreadChild = (t, path) => t.spreadElement(path.get('expression').node);
|
||||
const transformJSXSpreadChild = (
|
||||
path: NodePath<t.JSXSpreadChild>
|
||||
): t.SpreadElement => t.spreadElement(path.get('expression').node);
|
||||
|
||||
/**
|
||||
* Get JSX element type
|
||||
*
|
||||
* @param t
|
||||
* @param path Path<JSXOpeningElement>
|
||||
*/
|
||||
const getType = (t, path) => {
|
||||
const getType = (path: NodePath<t.JSXOpeningElement>) => {
|
||||
const typePath = path
|
||||
.get('attributes')
|
||||
.find(
|
||||
(attributePath) => t.isJSXAttribute(attributePath)
|
||||
&& t.isJSXIdentifier(attributePath.get('name'))
|
||||
&& attributePath.get('name.name').node === 'type'
|
||||
&& t.isStringLiteral(attributePath.get('value')),
|
||||
.find((attribute) => {
|
||||
if (!t.isJSXAttribute(attribute)) {
|
||||
return false;
|
||||
}
|
||||
return t.isJSXIdentifier(attribute.get('name'))
|
||||
&& (attribute.get('name') as NodePath<t.JSXIdentifier>).get('name') === 'type'
|
||||
&& t.isStringLiteral(attribute.get('value'))
|
||||
},
|
||||
);
|
||||
|
||||
return typePath ? typePath.get('value.value').node : '';
|
||||
return typePath ? typePath.get('value.value') : '';
|
||||
};
|
||||
|
||||
const resolveDirective = (t, path, state, tag, directiveName) => {
|
||||
const resolveDirective = (path: NodePath<t.JSXAttribute>, state: State, tag: any, directiveName: string) => {
|
||||
if (directiveName === 'show') {
|
||||
return createIdentifier(t, state, 'vShow');
|
||||
return createIdentifier(state, 'vShow');
|
||||
} if (directiveName === 'model') {
|
||||
let modelToUse;
|
||||
const type = getType(t, path.parentPath);
|
||||
const type = getType(path.parentPath as NodePath<t.JSXOpeningElement>);
|
||||
switch (tag.value) {
|
||||
case 'select':
|
||||
modelToUse = createIdentifier(t, state, 'vModelSelect');
|
||||
modelToUse = createIdentifier(state, 'vModelSelect');
|
||||
break;
|
||||
case 'textarea':
|
||||
modelToUse = createIdentifier(t, state, 'vModelText');
|
||||
modelToUse = createIdentifier(state, 'vModelText');
|
||||
break;
|
||||
default:
|
||||
switch (type) {
|
||||
case 'checkbox':
|
||||
modelToUse = createIdentifier(t, state, 'vModelCheckbox');
|
||||
modelToUse = createIdentifier(state, 'vModelCheckbox');
|
||||
break;
|
||||
case 'radio':
|
||||
modelToUse = createIdentifier(t, state, 'vModelRadio');
|
||||
modelToUse = createIdentifier(state, 'vModelRadio');
|
||||
break;
|
||||
default:
|
||||
modelToUse = createIdentifier(t, state, 'vModelText');
|
||||
modelToUse = createIdentifier(state, 'vModelText');
|
||||
}
|
||||
}
|
||||
return modelToUse;
|
||||
}
|
||||
return t.callExpression(
|
||||
createIdentifier(t, state, 'resolveDirective'), [
|
||||
createIdentifier(state, 'resolveDirective'), [
|
||||
t.stringLiteral(directiveName),
|
||||
],
|
||||
);
|
||||
@ -245,18 +227,25 @@ const resolveDirective = (t, path, state, tag, directiveName) => {
|
||||
/**
|
||||
* Parse directives metadata
|
||||
*
|
||||
* @param t
|
||||
* @param path JSXAttribute
|
||||
* @returns null | Object<{ modifiers: Set<string>, valuePath: Path<Expression>}>
|
||||
*/
|
||||
const parseDirectives = (t, {
|
||||
name, path, value, state, tag, isComponent,
|
||||
const parseDirectives = (args: {
|
||||
name: string,
|
||||
path: NodePath<t.JSXAttribute>,
|
||||
value: t.StringLiteral | t.Expression | null,
|
||||
state: State,
|
||||
tag: t.Identifier | t.MemberExpression | t.StringLiteral | t.CallExpression,
|
||||
isComponent: boolean
|
||||
}) => {
|
||||
const modifiers = name.split('_');
|
||||
const directiveName = modifiers.shift()
|
||||
.replace(/^v/, '')
|
||||
const {
|
||||
name, path, value, state, tag, isComponent,
|
||||
} = args
|
||||
const modifiers: string[] = name.split('_');
|
||||
const directiveName: string = modifiers.shift()
|
||||
?.replace(/^v/, '')
|
||||
.replace(/^-/, '')
|
||||
.replace(/^\S/, (s) => s.toLowerCase());
|
||||
.replace(/^\S/, (s: string) => s.toLowerCase()) || '';
|
||||
|
||||
if (directiveName === 'model' && !t.isJSXExpressionContainer(path.get('value'))) {
|
||||
throw new Error('You have to use JSX Expression inside your v-model');
|
||||
@ -270,10 +259,10 @@ const parseDirectives = (t, {
|
||||
directiveName,
|
||||
modifiers: modifiersSet,
|
||||
directive: hasDirective ? [
|
||||
resolveDirective(t, path, state, tag, directiveName),
|
||||
resolveDirective(path, state, tag, directiveName),
|
||||
value,
|
||||
modifiersSet.size && t.unaryExpression('void', t.numericLiteral(0), true),
|
||||
modifiersSet.size && t.objectExpression(
|
||||
!!modifiersSet.size && t.unaryExpression('void', t.numericLiteral(0), true),
|
||||
!!modifiersSet.size && t.objectExpression(
|
||||
[...modifiersSet].map(
|
||||
(modifier) => t.objectProperty(
|
||||
t.identifier(modifier),
|
||||
@ -281,7 +270,7 @@ const parseDirectives = (t, {
|
||||
),
|
||||
),
|
||||
),
|
||||
].filter(Boolean) : undefined,
|
||||
].filter(Boolean as any as ExcludesFalse) : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
@ -295,8 +284,6 @@ export {
|
||||
transformJSXText,
|
||||
transformJSXSpreadChild,
|
||||
transformJSXExpressionContainer,
|
||||
PatchFlags,
|
||||
PatchFlagNames,
|
||||
parseDirectives,
|
||||
isFragment,
|
||||
};
|
@ -3,6 +3,7 @@ import { shallowMount, mount } from '@vue/test-utils';
|
||||
|
||||
const patchFlagExpect = (wrapper, flag, dynamic) => {
|
||||
const { patchFlag, dynamicProps } = wrapper.vm.$.subTree;
|
||||
|
||||
expect(patchFlag).toBe(flag);
|
||||
expect(dynamicProps).toEqual(dynamic);
|
||||
};
|
||||
|
13
packages/babel-plugin-jsx/tsconfig.json
Normal file
13
packages/babel-plugin-jsx/tsconfig.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDirs": ["./src"],
|
||||
"outDir": "dist",
|
||||
"downlevelIteration": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"global.d.ts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
Reference in New Issue
Block a user