chushihua
This commit is contained in:
+208
@@ -0,0 +1,208 @@
|
||||
# babel-plugin-transform-vue-jsx [](https://circleci.com/gh/vuejs/babel-plugin-transform-vue-jsx)
|
||||
|
||||
> Babel plugin for Vue 2.0 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
|
||||
|
||||
``` bash
|
||||
npm install\
|
||||
babel-plugin-syntax-jsx\
|
||||
babel-plugin-transform-vue-jsx\
|
||||
babel-helper-vue-jsx-merge-props\
|
||||
babel-preset-env\
|
||||
--save-dev
|
||||
```
|
||||
|
||||
In your `.babelrc`:
|
||||
|
||||
``` json
|
||||
{
|
||||
"presets": ["env"],
|
||||
"plugins": ["transform-vue-jsx"]
|
||||
}
|
||||
```
|
||||
|
||||
The plugin transpiles the following JSX:
|
||||
|
||||
``` jsx
|
||||
<div id="foo">{this.text}</div>
|
||||
```
|
||||
|
||||
To the following JavaScript:
|
||||
|
||||
``` js
|
||||
h('div', {
|
||||
attrs: {
|
||||
id: 'foo'
|
||||
}
|
||||
}, [this.text])
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
``` js
|
||||
Vue.component('jsx-example', {
|
||||
render (h) { // <-- h must be in scope
|
||||
return <div id="foo">bar</div>
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### `h` auto-injection
|
||||
|
||||
Starting with version 3.4.0 we automatically inject `const h = this.$createElement` in any method and getter (not functions or arrow functions) declared in ES2015 syntax that has JSX so you can drop the `(h)` parameter.
|
||||
|
||||
``` js
|
||||
|
||||
Vue.component('jsx-example', {
|
||||
render () { // h will be injected
|
||||
return <div id="foo">bar</div>
|
||||
},
|
||||
myMethod: function () { // h will not be injected
|
||||
return <div id="foo">bar</div>
|
||||
},
|
||||
someOtherMethod: () => { // h will not be injected
|
||||
return <div id="foo">bar</div>
|
||||
}
|
||||
})
|
||||
|
||||
@Component
|
||||
class App extends Vue {
|
||||
get computed () { // h will be injected
|
||||
return <div id="foo">bar</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
``` js
|
||||
render (h) {
|
||||
return h('div', {
|
||||
// Component props
|
||||
props: {
|
||||
msg: 'hi'
|
||||
},
|
||||
// normal HTML attributes
|
||||
attrs: {
|
||||
id: 'foo'
|
||||
},
|
||||
// DOM props
|
||||
domProps: {
|
||||
innerHTML: 'bar'
|
||||
},
|
||||
// Event handlers are nested under "on", though
|
||||
// modifiers such as in v-on:keyup.enter are not
|
||||
// supported. You'll have to manually check the
|
||||
// keyCode in the handler instead.
|
||||
on: {
|
||||
click: this.clickHandler
|
||||
},
|
||||
// For components only. Allows you to listen to
|
||||
// native events, rather than events emitted from
|
||||
// the component using vm.$emit.
|
||||
nativeOn: {
|
||||
click: this.nativeClickHandler
|
||||
},
|
||||
// class is a special module, same API as `v-bind:class`
|
||||
class: {
|
||||
foo: true,
|
||||
bar: false
|
||||
},
|
||||
// style is also same as `v-bind:style`
|
||||
style: {
|
||||
color: 'red',
|
||||
fontSize: '14px'
|
||||
},
|
||||
// other special top-level properties
|
||||
key: 'key',
|
||||
ref: 'ref',
|
||||
// assign the `ref` is used on elements/components with v-for
|
||||
refInFor: true,
|
||||
slot: 'slot'
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The equivalent of the above in Vue 2.0 JSX is:
|
||||
|
||||
``` jsx
|
||||
render (h) {
|
||||
return (
|
||||
<div
|
||||
// normal attributes or component props.
|
||||
id="foo"
|
||||
// DOM properties are prefixed with `domProps`
|
||||
domPropsInnerHTML="bar"
|
||||
// event listeners are prefixed with `on` or `nativeOn`
|
||||
onClick={this.clickHandler}
|
||||
nativeOnClick={this.nativeClickHandler}
|
||||
// other special top-level properties
|
||||
class={{ foo: true, bar: false }}
|
||||
style={{ color: 'red', fontSize: '14px' }}
|
||||
key="key"
|
||||
ref="ref"
|
||||
// assign the `ref` is used on elements/components with v-for
|
||||
refInFor
|
||||
slot="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:
|
||||
|
||||
``` js
|
||||
import Todo from './Todo.js'
|
||||
|
||||
export default {
|
||||
render (h) {
|
||||
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:
|
||||
|
||||
``` jsx
|
||||
const data = {
|
||||
class: ['b', 'c']
|
||||
}
|
||||
const vnode = <div class="a" {...data}/>
|
||||
```
|
||||
|
||||
The merged data will be:
|
||||
|
||||
``` js
|
||||
{ class: ['a', 'b', 'c'] }
|
||||
```
|
||||
|
||||
### Vue directives
|
||||
|
||||
Note that almost all built-in Vue directives are not supported when using JSX, the sole exception being `v-show`, which can be used with the `v-show={value}` syntax. In most cases there are obvious programmatic equivalents, for example `v-if` is just a ternary expression, and `v-for` is just an `array.map()` expression, etc.
|
||||
|
||||
For custom directives, you can use the `v-name={value}` syntax. However, note that directive arguments and modifiers are not supported using this syntax. There are two workarounds:
|
||||
|
||||
1. Pass everything as an object via `value`, e.g. `v-name={{ value, modifier: true }}`
|
||||
|
||||
2. Use the raw vnode directive data format:
|
||||
|
||||
``` js
|
||||
const directives = [
|
||||
{ name: 'my-dir', value: 123, modifiers: { abc: true } }
|
||||
]
|
||||
|
||||
return <div {...{ directives }}/>
|
||||
```
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+223
@@ -0,0 +1,223 @@
|
||||
var esutils = require('esutils')
|
||||
var groupProps = require('./lib/group-props')
|
||||
var mustUseProp = require('./lib/must-use-prop')
|
||||
|
||||
var isInsideJsxExpression = function (t, path) {
|
||||
if (!path.parentPath) {
|
||||
return false
|
||||
}
|
||||
if (t.isJSXExpressionContainer(path.parentPath)) {
|
||||
return true
|
||||
}
|
||||
return isInsideJsxExpression(t, path.parentPath)
|
||||
}
|
||||
|
||||
module.exports = function (babel) {
|
||||
var t = babel.types
|
||||
|
||||
return {
|
||||
inherits: require('babel-plugin-syntax-jsx'),
|
||||
visitor: {
|
||||
JSXNamespacedName (path) {
|
||||
throw path.buildCodeFrameError(
|
||||
'Namespaced tags/attributes are not supported. JSX is not XML.\n' +
|
||||
'For attributes like xlink:href, use xlinkHref instead.'
|
||||
)
|
||||
},
|
||||
JSXElement: {
|
||||
exit (path, file) {
|
||||
// turn tag into createElement call
|
||||
var callExpr = buildElementCall(path.get('openingElement'), file)
|
||||
if (path.node.children.length) {
|
||||
// add children array as 3rd arg
|
||||
callExpr.arguments.push(t.arrayExpression(path.node.children))
|
||||
if (callExpr.arguments.length >= 3) {
|
||||
callExpr._prettyCall = true
|
||||
}
|
||||
}
|
||||
path.replaceWith(t.inherits(callExpr, path.node))
|
||||
}
|
||||
},
|
||||
'Program' (path) {
|
||||
path.traverse({
|
||||
'ObjectMethod|ClassMethod' (path) {
|
||||
const params = path.get('params')
|
||||
// do nothing if there is (h) param
|
||||
if (params.length && params[0].node.name === 'h') {
|
||||
return
|
||||
}
|
||||
// do nothing if there is no JSX inside
|
||||
const jsxChecker = {
|
||||
hasJsx: false
|
||||
}
|
||||
path.traverse({
|
||||
JSXElement () {
|
||||
this.hasJsx = true
|
||||
}
|
||||
}, jsxChecker)
|
||||
if (!jsxChecker.hasJsx) {
|
||||
return
|
||||
}
|
||||
// do nothing if this method is a part of JSX expression
|
||||
if (isInsideJsxExpression(t, path)) {
|
||||
return
|
||||
}
|
||||
const isRender = path.node.key.name === 'render'
|
||||
// inject h otherwise
|
||||
path.get('body').unshiftContainer('body', t.variableDeclaration('const', [
|
||||
t.variableDeclarator(
|
||||
t.identifier('h'),
|
||||
(
|
||||
isRender
|
||||
? t.memberExpression(
|
||||
t.identifier('arguments'),
|
||||
t.numericLiteral(0),
|
||||
true
|
||||
)
|
||||
: t.memberExpression(
|
||||
t.thisExpression(),
|
||||
t.identifier('$createElement')
|
||||
)
|
||||
)
|
||||
)
|
||||
]))
|
||||
},
|
||||
JSXOpeningElement (path) {
|
||||
const tag = path.get('name').node.name
|
||||
const attributes = path.get('attributes')
|
||||
const typeAttribute = attributes.find(attributePath => attributePath.node.name && attributePath.node.name.name === 'type')
|
||||
const type = typeAttribute && t.isStringLiteral(typeAttribute.node.value) ? typeAttribute.node.value.value : null
|
||||
|
||||
attributes.forEach(attributePath => {
|
||||
const attribute = attributePath.get('name')
|
||||
|
||||
if (!attribute.node) {
|
||||
return
|
||||
}
|
||||
|
||||
const attr = attribute.node.name
|
||||
|
||||
if (mustUseProp(tag, type, attr) && t.isJSXExpressionContainer(attributePath.node.value)) {
|
||||
attribute.replaceWith(t.JSXIdentifier(`domProps-${attr}`))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildElementCall (path, file) {
|
||||
path.parent.children = t.react.buildChildren(path.parent)
|
||||
var tagExpr = convertJSXIdentifier(path.node.name, path.node)
|
||||
var args = []
|
||||
|
||||
var tagName
|
||||
if (t.isIdentifier(tagExpr)) {
|
||||
tagName = tagExpr.name
|
||||
} else if (t.isLiteral(tagExpr)) {
|
||||
tagName = tagExpr.value
|
||||
}
|
||||
|
||||
if (t.react.isCompatTag(tagName)) {
|
||||
args.push(t.stringLiteral(tagName))
|
||||
} else {
|
||||
args.push(tagExpr)
|
||||
}
|
||||
|
||||
var attribs = path.node.attributes
|
||||
if (attribs.length) {
|
||||
attribs = buildOpeningElementAttributes(attribs, file)
|
||||
args.push(attribs)
|
||||
}
|
||||
return t.callExpression(t.identifier('h'), args)
|
||||
}
|
||||
|
||||
function convertJSXIdentifier (node, parent) {
|
||||
if (t.isJSXIdentifier(node)) {
|
||||
if (node.name === 'this' && t.isReferenced(node, parent)) {
|
||||
return t.thisExpression()
|
||||
} else if (esutils.keyword.isIdentifierNameES6(node.name)) {
|
||||
node.type = 'Identifier'
|
||||
} else {
|
||||
return t.stringLiteral(node.name)
|
||||
}
|
||||
} else if (t.isJSXMemberExpression(node)) {
|
||||
return t.memberExpression(
|
||||
convertJSXIdentifier(node.object, node),
|
||||
convertJSXIdentifier(node.property, node)
|
||||
)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
/**
|
||||
* The logic for this is quite terse. It's because we need to
|
||||
* support spread elements. We loop over all attributes,
|
||||
* breaking on spreads, we then push a new object containing
|
||||
* all prior attributes to an array for later processing.
|
||||
*/
|
||||
|
||||
function buildOpeningElementAttributes (attribs, file) {
|
||||
var _props = []
|
||||
var objs = []
|
||||
|
||||
function pushProps () {
|
||||
if (!_props.length) return
|
||||
objs.push(t.objectExpression(_props))
|
||||
_props = []
|
||||
}
|
||||
|
||||
while (attribs.length) {
|
||||
var prop = attribs.shift()
|
||||
if (t.isJSXSpreadAttribute(prop)) {
|
||||
pushProps()
|
||||
prop.argument._isSpread = true
|
||||
objs.push(prop.argument)
|
||||
} else {
|
||||
_props.push(convertAttribute(prop))
|
||||
}
|
||||
}
|
||||
|
||||
pushProps()
|
||||
|
||||
objs = objs.map(function (o) {
|
||||
return o._isSpread ? o : groupProps(o.properties, t)
|
||||
})
|
||||
|
||||
if (objs.length === 1) {
|
||||
// only one object
|
||||
attribs = objs[0]
|
||||
} else if (objs.length) {
|
||||
// add prop merging helper
|
||||
var helper = file.addImport('babel-helper-vue-jsx-merge-props', 'default', '_mergeJSXProps')
|
||||
// spread it
|
||||
attribs = t.callExpression(
|
||||
helper,
|
||||
[t.arrayExpression(objs)]
|
||||
)
|
||||
}
|
||||
return attribs
|
||||
}
|
||||
|
||||
function convertAttribute (node) {
|
||||
var value = convertAttributeValue(node.value || t.booleanLiteral(true))
|
||||
if (t.isStringLiteral(value) && !t.isJSXExpressionContainer(node.value)) {
|
||||
value.value = value.value.replace(/\n\s+/g, ' ')
|
||||
}
|
||||
if (t.isValidIdentifier(node.name.name)) {
|
||||
node.name.type = 'Identifier'
|
||||
} else {
|
||||
node.name = t.stringLiteral(node.name.name)
|
||||
}
|
||||
return t.inherits(t.objectProperty(node.name, value), node)
|
||||
}
|
||||
|
||||
function convertAttributeValue (node) {
|
||||
if (t.isJSXExpressionContainer(node)) {
|
||||
return node.expression
|
||||
} else {
|
||||
return node
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
var makeMap = require('./make-map')
|
||||
var isTopLevel = makeMap('class,staticClass,style,key,ref,refInFor,slot,scopedSlots')
|
||||
var nestableRE = /^(props|domProps|on|nativeOn|hook)([\-_A-Z])/
|
||||
var dirRE = /^v-/
|
||||
var xlinkRE = /^xlink([A-Z])/
|
||||
|
||||
module.exports = function groupProps (props, t) {
|
||||
var newProps = []
|
||||
var currentNestedObjects = Object.create(null)
|
||||
props.forEach(function (prop) {
|
||||
var name = prop.key.value || prop.key.name
|
||||
if (isTopLevel(name)) {
|
||||
// top-level special props
|
||||
newProps.push(prop)
|
||||
} else {
|
||||
// nested modules
|
||||
var nestMatch = name.match(nestableRE)
|
||||
if (nestMatch) {
|
||||
var prefix = nestMatch[1]
|
||||
var suffix = name.replace(nestableRE, function (_, $1, $2) {
|
||||
return $2 === '-' ? '' : $2.toLowerCase()
|
||||
})
|
||||
var nestedProp = t.objectProperty(t.stringLiteral(suffix), prop.value)
|
||||
var nestedObject = currentNestedObjects[prefix]
|
||||
if (!nestedObject) {
|
||||
nestedObject = currentNestedObjects[prefix] = t.objectProperty(
|
||||
t.identifier(prefix),
|
||||
t.objectExpression([nestedProp])
|
||||
)
|
||||
newProps.push(nestedObject)
|
||||
} else {
|
||||
nestedObject.value.properties.push(nestedProp)
|
||||
}
|
||||
} else if (dirRE.test(name)) {
|
||||
// custom directive
|
||||
name = name.replace(dirRE, '')
|
||||
var dirs = currentNestedObjects.directives
|
||||
if (!dirs) {
|
||||
dirs = currentNestedObjects.directives = t.objectProperty(
|
||||
t.identifier('directives'),
|
||||
t.arrayExpression([])
|
||||
)
|
||||
newProps.push(dirs)
|
||||
}
|
||||
dirs.value.elements.push(t.objectExpression([
|
||||
t.objectProperty(
|
||||
t.identifier('name'),
|
||||
t.stringLiteral(name)
|
||||
),
|
||||
t.objectProperty(
|
||||
t.identifier('value'),
|
||||
prop.value
|
||||
)
|
||||
]))
|
||||
} else {
|
||||
// rest are nested under attrs
|
||||
var attrs = currentNestedObjects.attrs
|
||||
// guard xlink attributes
|
||||
if (xlinkRE.test(prop.key.name)) {
|
||||
prop.key.name = JSON.stringify(prop.key.name.replace(xlinkRE, function (m, p1) {
|
||||
return 'xlink:' + p1.toLowerCase()
|
||||
}))
|
||||
}
|
||||
if (!attrs) {
|
||||
attrs = currentNestedObjects.attrs = t.objectProperty(
|
||||
t.identifier('attrs'),
|
||||
t.objectExpression([prop])
|
||||
)
|
||||
newProps.push(attrs)
|
||||
} else {
|
||||
attrs.value.properties.push(prop)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return t.objectExpression(newProps)
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
module.exports = function makeMap (str) {
|
||||
var map = Object.create(null)
|
||||
var list = str.split(',')
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
map[list[i]] = true
|
||||
}
|
||||
return val => map[val]
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
const acceptValue = ['input','textarea','option','select']
|
||||
module.exports = (tag, type, attr) => {
|
||||
return (
|
||||
(attr === 'value' && acceptValue.includes(tag)) && type !== 'button' ||
|
||||
(attr === 'selected' && tag === 'option') ||
|
||||
(attr === 'checked' && tag === 'input') ||
|
||||
(attr === 'muted' && tag === 'video')
|
||||
)
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "babel-plugin-transform-vue-jsx",
|
||||
"version": "3.7.0",
|
||||
"description": "Babel plugin for Vue 2.0 JSX",
|
||||
"main": "index.js",
|
||||
"unpkg": "dist/babel-plugin-transform-vue-jsx.min.js",
|
||||
"files": [
|
||||
"index.js",
|
||||
"lib",
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"lint": "eslint index.js",
|
||||
"test": "npm run lint && mocha --compilers js:babel-register",
|
||||
"dev": "cd example && webpack --watch",
|
||||
"build": "webpack -p index.js dist/babel-plugin-transform-vue-jsx.min.js --target=web --output-library=babel-plugin-transform-vue-jsx --output-library-target=umd --module-bind 'js=babel-loader'",
|
||||
"prepublish": "npm run build"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vuejs/babel-plugin-transform-vue-jsx.git"
|
||||
},
|
||||
"keywords": [
|
||||
"vue",
|
||||
"babel",
|
||||
"jsx"
|
||||
],
|
||||
"author": "Evan You",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/vuejs/babel-plugin-transform-vue-jsx/issues"
|
||||
},
|
||||
"homepage": "https://github.com/vuejs/babel-plugin-transform-vue-jsx#readme",
|
||||
"dependencies": {
|
||||
"esutils": "^2.0.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"babel-helper-vue-jsx-merge-props": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-cli": "^6.26.0",
|
||||
"babel-core": "^6.26.0",
|
||||
"babel-helper-vue-jsx-merge-props": "^2.0.3",
|
||||
"babel-loader": "^7.1.2",
|
||||
"babel-plugin-syntax-jsx": "^6.18.0",
|
||||
"babel-preset-es2015": "^6.24.1",
|
||||
"babel-register": "^6.26.0",
|
||||
"chai": "^4.1.2",
|
||||
"eslint": "^4.16.0",
|
||||
"eslint-plugin-vue-libs": "^2.1.0",
|
||||
"mocha": "^5.0.0",
|
||||
"vue": "^2.5.13",
|
||||
"webpack": "^3.10.0"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user