@vue/babel-plugin-transform-vue-jsx
Babel plugin for Vue 2.0 JSX
Babel Compatibility Notes
- This repo is only compatible with Babel 7.x, for 6.x please use vuejs/babel-plugin-transform-vue-jsx
Requirements
-
Assumes you are using Babel with a module bundler e.g. Webpack, because the spread merge helper is imported as a module to avoid duplication.
-
This is mutually exclusive with
babel-plugin-transform-react-jsx
.
Usage
npm install @vue/babel-plugin-transform-vue-jsx --save-devnpm install @vue/babel-helper-vue-jsx-merge-props --save
In your .babelrc
:
However it is recommended to use the configurable preset instead.
Details
The plugin transpiles the following JSX:
<div ="foo">thistext</div>
To the following JavaScript:
Note the h
function, which is a shorthand for a Vue instance's $createElement
method, must be in the scope where the JSX is. Since this method is passed to component render functions as the first argument, in most cases you'd do this:
Vue
Difference from React JSX
First, Vue 2.0's vnode format is different from React's. The second argument to the createElement
call is a "data object" that accepts nested objects. Each nested object will be then processed by corresponding modules:
{ return }
The equivalent of the above in Vue 2.0 JSX is:
{ return <div // ="hi" // . ="foo" // `` ="bar" // `` `` = = // = = ="key" ="ref" // `` / ="slot"> </div> }
Component Tip
If a custom element starts with lowercase, it will be treated as a string id and used to lookup a registered component. If it starts with uppercase, it will be treated as an identifier, which allows you to do:
{ return <Todo /> // no need to register Todo via components option }
JSX Spread
JSX spread is supported, and this plugin will intelligently merge nested data properties. For example:
const data = class: 'b' 'c'const vnode = <div ="a" />
The merged data will be:
class: 'a' 'b' 'c'
Vue directives
Vue directives are usable the same way as in template with a few key differences:
- You can use directives camelCased instead of kebab-cased (vMyDirective is treated as
v-my-directive
) - You have to use underscore sign instead of dots for modifiers because of JSXIdentifier limitation.
- Only runtime directives work (only v-show and custom directives), compile-time directives are out of this project's scope.
A full example would be: <MyComponent vMyDirective:argument_modifier1_modifier2={someExpression} />