vuejs / babel-plugin-transform-vue-jsx Goto Github PK
View Code? Open in Web Editor NEWbabel plugin for vue 2.0 jsx
babel plugin for vue 2.0 jsx
<Pagination style={{marginTop: '16px', marginBottom: '16px', float: 'right'}} layout="prev, pager, next" pageSize={this.pagination.pageSize} total={this.total}> onClick={this.handleClick} nativeOnClick={this.handleClick} </Pagination>
babel ====>
h( _elementUi.Pagination, { style: { marginTop: '16px', marginBottom: '16px', float: 'right' }, attrs: { layout: 'prev, pager, next', pageSize: this.pagination.pageSize, total: this.total } }, ['onClick=', this.handleClick, 'nativeOnClick=', this.handleClick] )
as title~
my component code here:
import dropDownMixin from './drop-down-mixin'
export default {
name: 'x-drop-down-menu',
mixins: [dropDownMixin],
functional: true,
render(h, context) {
let {
options, onItemClick, ...rest
} = context.props
console.log(rest)
return (
<x-drop-down {...rest}>
<div class="dropdown-menu">
{
options.map((item, index) => {
return (
<x-menu-item
onClick={ () => { onItemClick(item) } }
params={{ index, item }}
href="#">{item.label}
</x-menu-item>
)
})
}
</div>
</x-drop-down>
)
},
props: {
onItemClick: {
type: Function,
default: () => {}
},
// example: {label: label, text: text, divider: true}
options: {
type: Array,
default: () => []
}
}
}
and it will be compiled to:
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _dropDownMixin = require('./drop-down-mixin');
var _dropDownMixin2 = _interopRequireDefault(_dropDownMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'x-drop-down-menu',
mixins: [_dropDownMixin2.default],
functional: true,
render: function render(h, context) {
var _context$props = context.props;
var options = _context$props.options;
var onItemClick = _context$props.onItemClick;
var rest = (0, _objectWithoutProperties3.default)(_context$props, ['options', 'onItemClick']);
console.log(rest);
return h(
'x-drop-down',
rest,
[h(
'div',
{ 'class': 'dropdown-menu' },
[options.map(function (item, index) {
return h(
'x-menu-item',
{
attrs: {
onClick: function onClick() {
onItemClick(item);
},
params: { index: index, item: item },
href: '#' }
},
[item.label]
);
})]
)]
);
},
props: {
onItemClick: {
type: Function,
default: function _default() {}
},
// example: {label: label, text: text, divider: true}
options: {
type: Array,
default: function _default() {
return [];
}
}
}
};
and the rest object is:
{
alignment: "left"
btnType: "danger"
disabled: false
}
seems good
but my x-drop-down component can't get any props form it.
what should I do now?
As example:
const Ctor = Vue.extend(Component)
// doesn't work
const vm = new Ctor({ propsData: {
onChange: (...)
}}).$mount()
// works fine
vm.$on('change', (...))
i was wondering why cant we align with react jsx syntax?
ERROR in Cannot find module 'babel-runtime/helpers/interop-require'
@ multi app
import Child from './child'
...
methods: {
handleClick(){
}
},
render(h) {
<div>
<Child on-click={this.handleClick} />
</div>
}
<input @keyup.delete="deleteAction">
to jsx
<input onKeyup.delete={this.deleteAction}>
how to do keyup.delete in jsx
<Component>
{[]}
</Component>
// component.js
render() {
this.$slots.default // undefined, but expect get an empty []
}
Tried:
var elixir = require('laravel-elixir');
elixir.config.js.browserify.transformers.push({
name: 'babel-plugin-transform-vue-jsx'
});
Got:
dest.on('unpipe', onunpipe);
^
TypeError: dest.on is not a function
at DestroyableTransform.Readable.pipe (/Users/matanya/Sites/vue-tables-2/node_modules/module-deps/node_modules/readable-stream/lib/_stream_readable.js:527:8)
at wrapTransform (/Users/matanya/Sites/vue-tables-2/node_modules/module-deps/index.js:543:11)
at makeTransform (/Users/matanya/Sites/vue-tables-2/node_modules/module-deps/index.js:253:32)
at /Users/matanya/Sites/vue-tables-2/node_modules/module-deps/index.js:226:9
at Deps.getTransforms (/Users/matanya/Sites/vue-tables-2/node_modules/module-deps/index.js:231:7)
at /Users/matanya/Sites/vue-tables-2/node_modules/module-deps/index.js:366:24
at onresolve (/Users/matanya/Sites/vue-tables-2/node_modules/module-deps/index.js:178:14)
at /Users/matanya/Sites/vue-tables-2/node_modules/browserify/index.js:487:17
at LOOP (fs.js:1739:14)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
I have a component Card:
const style = {
...
};
export default {
name: 'CardComponent',
functional: true,
props: {
style: Object,
},
render: (h, {props, children}) => {
console.log('style', props.style);
return (
<div style={{...style}}>
{children}
</div>
);
},
};
And I reference it in another component SidePanel:
import Card from '../components/card';
const styles = {
...
card: {
height: '200px',
width: '100px',
},
};
export default {
name: 'SidePanelContainer',
render(h) {
return (
<div style={styles.container}>
<Card style={styles.card}>
<span>1</span>
</Card>
</div>
);
},
};
From the console.log in CardComponent.render props.style
is undefined. If I change the prop name then I can access the prop as normal.
This isn't a breaking issue, but for the sake of consistency I'd like to be able to pass custom styles as style
on both custom and non-custom components alike.
Not sure if this is intended or a bug.
versions:
"vue": "^2.1.10",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-vue-jsx": "^3.3.0",
"babel-helper-vue-jsx-merge-props": "^2.0.2",
is vue-jsx must Uppercase import Var first Letter it can just find the index.js file ?
import sidebar from 'components/sidebar/container'
export default {
render(h) {
return (
<div>
<sidebar></sidebar>
<p>
{console.log(sidebar)}
</p>
</div>
)
}
}
get error :
Object {name: "sidebar"}
vue.runtime.common.js?d43f:521 [Vue warn]: Unknown custom element: <sidebar> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
(found in anonymous component - use the "name" option for better debugging messages.)
as you can see : i just echo my sidebar render . is that a bug ?
but i just change my import Var to Sidebar and use <Sidebar/> ervery thing is work fine.
if my folder tree like below :
sidebar --folder
|--------container.js
|--------top-icon.js
|--------menu.js
|--------footer.js
is just use components:{} option or have anthor good way , i want find Figure out .
is it possible to add support for xlink:href attribute, because currently can't use <use>
tag because of the warning - Namespace tags are not supported. JSX is not XML.
Example of simple icon component:
render(h, context) {
const name = context.props.name;
return (
<svg class={`icon icon-${name}`}>
<use xlink:href={`#${name}`}></use>
</svg>
);
},
Hello,
I am trying to migrate to Vue 2 and for this I need to use the vue-tables-2 component. I am using Laravel Elixir with webpack to compile my Vue projects. I followed the instructions and installed babel-plugin-transform-vue-jsx and its dependencies and create the .babelrc at the same level as the script. The below error is displayed :
Error: ./~/vue-tables-2/lib/template.jsx
Module build failed: SyntaxError: Unexpected token (15:7)
The corresponding character is <
Do you have any advice ?
Thanks
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.component('jsx-example', {
render (h) { // <-- h must be in scope
return <div id="foo">bar</div>
}
})
I just want to know why it is called h
and how to remember it :)
Now that on* are interpreted as events, props that look like that don't get passed through. I very often pass in callbacks like "onSave", etc.
Hi,
i'm writing my vue component with coffeescript.
With react I used to use cjsx : https://github.com/jsdf/coffee-react-transform
I would love to use something similar for my vue files. Is it planed on any roadmap ?
If I want to do it by myself, do you have any advices on where to start ? (i'm a bit lost in the babel ecosystem)
thanks
Suppose a component is designed like this:
const Select = {
name: 'Select',
props: {
...,
onChange: {
type: Function,
},
},
}
And then for use example:
<Select onChange={e=>(...)} />
That's mean I expect to pass props
rather than bind change
event.
like it
Vue.component('jsx-example', {
props: ['name'],
render: (h)=> {
return <div>{this.name}</div>
}
})
result
....
render: function render(h) {
return h(
"div",
[undefined.name]
)
}
....
This requires exposing the 'createElement' function under 'Vue', it makes for a cleaner syntax. For now a workaround is this:
var h;
new Vue({ render : function (x) { h = x; });
Hey Vue team,
Very nice work on everything with 2.0. So far, it's been awesome to use!
I just tried to use the spread operator with props, and I'm getting an error. I've verified that the spread operator is working correctly in other places, and I've also verified that the props are being passed in correctly.
Here's the error that I am getting:
Thanks again for the great work with 2.0!
Vue: v2.0.0-beta.7
babel-plugin-transform-vue-jsx: v3.1.0
How to resolve this warning?
ERROR in ./example.js
Module build failed: Error: Couldn't find preset "es2015" relative to directory "D:\me\vue\babel-plugin-transform-vue-jsx"
at D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\options\option-manager.js:299:19
at Array.map (native)
at OptionManager.resolvePresets (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\options\option-manager.js:270:20)
at OptionManager.mergePresets (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\options\option-manager.js:259:10)
at OptionManager.mergeOptions (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\options\option-manager.js:244:14)
at OptionManager.init (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\options\option-manager.js:374:12)
at File.initOptions (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\index.js:216:65)
at new File (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\file\index.js:139:24)
at Pipeline.transform (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
at transpile (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-loader\lib\index.js:41:20)
at Object.module.exports (D:\me\vue\babel-plugin-transform-vue-jsx\example\node_modules\babel-loader\lib\index.js:138:12)
I think each dash attribute as well:
render(h) {
return (
<div data-id="foo" />
)
}
output:
<div></div>
It's a solution, but incovenient and doesn't make sense
render(h) {
return (
<div {...{attrs: {'data-id': 'foo'}}} />
)
}
<input v-model="data1" />
data(){
return {
data1: ''
};
}
how to write jsx .
i try to use
h('input',{directives:[{name:'v-model',value:'data1'}]})
not report error .
thx.
Reproduction Repo: https://github.com/znck/example-functional-rollup-plugin-vue
Original issue: znck/rollup-plugin-vue#51
JSX Transform
Thank you @znck, this plugin is very much needed!
After the error ReferenceError: React is not defined and LOL I can confirm the plugin doesn't support JSX transformation and somehow uses the React one. I can even see in yarn.lock the react references, although is not a direct dependency.
I am not sure about the solution, relatively new to Rollup and bundlers plugins, but would like to help in any matter possible, so let me know!
Is there an example for typescript developer?
I'm having issues when trying to access elements in the $refs. The docs don't seem to suggest any different usage.
render(h) {
console.log(this.$refs);
// Returns { element: theNode }
console.log(this.$refs.element)
// Returns undefined
console.log(Object.values(this.$refs));
// Returns [] (empty array)
return (
<div ref="element">
</div>
)
}
We could do something like:
render (h) {
return <div onKeyup.enter={this.something} />
}
render (h) {
return h('div', {
on: {
keyup: {
enter: this.something
}
}
}
}
to support the event modifiers, what do you think @yyx990803, @QingWei-Li, does it make any sense to you ?
I noticed that render function is called by the current vm (See vue.runtime.common.js#L2216). Maybe we can replace h
to this.$createElement
? We can remove "ugly" h
.
I can submit PR if you agree.
<my-input nativeOn-keydown.up={this.handleKeydownUp}></my-input>
just like above, it dosen't work.
In some nested components case, we don't want to pass slot
from outside, cloud we defined in component first?
const Compo = {
render(h) {
return (
<div slot="foo">
</div>
)
}
}
Is it possible to use Vue JSX inside a jsfiddle or codepen demo? I am trying to use it in codepen. I have the babel preprocessor selected and a cdn to the latest beta of Vue 2.0. But it doesn't seem to work. As it stands now, the only way to play around with Vue JSX is to setup a basic webpack project similar to the example provided in this repo?
Basically as the title says I'm wondering how we are meant to work with form inputs?
As an example here's me trying to work with a checkbox element which is rendered in a loop.
/* A test button to trigger it */
<button onClick={e => this.changeGoal(p.id)}>Mark It</button>
/* Text state */
<p>{this.isSelected(p) ? 'checked' : 'unchecked'}</p>
/* The checkbox */
<input type="checkbox" value={p.id} class="changeGoalTest"
onClick={e => this.changeGoal(p.id)}
checked={this.isSelected(p)}/>
The changeGoal method just updates the selected goal, and the isSelected.. well you get the idea.
Anyway, if I have four items that get spat out, upon clicking on the first button
this loops text updates to checked
and the checkbox is indeed checked.
Clicking on the second button
the first item reverts it's state and the second item now shows the checked
text and the checkbox is indeed checked. This holds true for three and four.
However if we click on the checkboxes
the previously checked boxes do not uncheck however the text above them does change.
I attempted to change my onClick handler to the below version, however it made no difference.
onClick={e => {e.preventDefault(); this.changeGoal(p.id)}}`
I tried swapping the onClick
out for nativeOnClick
and it refused to trigger at all.
export default { render(h) { //eslint-disable-line no-unused-vars return ( <aside transition="expand"> <ShortDesc /> </aside> ); } };
Hello, as title, how can I use v-for
or v-if
in jsx!Just like this:
<ul class="header_nav_list">
<li v-for="(item, index) in nav" class={{ header_nav_item: true, active: this.activeNav === item.type }}>{item.name}</li>
</ul>
I just got an error ReferenceError: item is not defined
I was trying a bunch of things like:
<div class={['nations', 'detail', { 'loading': this.loading }]}>
<div class={'nations', 'detail', { 'loading': this.loading }}>
<div class="'nations detail { 'loading': this.loading }">
etc. to no avail, what is the correct way? :)
Here is my code:
export const _isComponent = (tab) => tab.hasOwnProperty('component')
export const _askedForPassedProps = (tab) => tab.hasOwnProperty('props')
const TabContentWrapper = {
functional: true,
name: "TabContentWrapper",
props: {
// tabs: {
// type: Array,
// required: true
// },
//
// activeTab: {
// type: Number,
// required: true
// },
},
render (h, context) {
const props = context.data.attrs,
tabs = props.tabs,
activeTab = props["active-tab"],
contents = tabs.map( (_tab, index) => {
const isComponent = _isComponent(_tab),
isShown = index === activeTab
let askedProps = _askedForPassedProps(_tab) && _tab.props,
finalProps = {}
if (askedProps) {
_.each(askedProps, (prop) => finalProps[prop] = props[prop])
}
const data = { 'props': finalProps }
debugger
return isComponent ?
<_tab.component v-show={isShown} {...data}></_tab.component> :
<router-view v-show={isShown} name={_tab.name} {...finalProps}></router-view>
})
return (
<div class="tab-content">
{contents}
</div>
)
}
}
export default TabContentWrapper
None of the techniques used to inject props works ๐ข
I got ReferenceError: h is not defined
inside my render()
method defined in the class component (with vue-class-component) when using v3.4.1.
h
should be auto-injected here, but I don't know why the output of babel missed the part of injection.
.babelrc:
{
"presets": ["es2015"],
"plugins": [
"transform-decorators-legacy",
"transform-class-properties",
"transform-vue-jsx"
]
}
part of my babel output:
...
_createClass(_default, [{
key: 'created',
value: function created() {
this.fetchData();
}
}, {
key: 'render',
value: function render() { // missing injection of `h`
return h(
...
I know React needs the React
variable available, thus Vue requires something similar but still feels hacky...
Shouldn't it be enough to transpile to this.$createElement
directly? Or couldn't just the plugin to create a variable on the fly and use it?
I'm not sure what Babel plugins are capable of. ๐
Regards,
key: 'key',
ref: 'ref',
refInFor: true,
what is these three option do ?
if possible , can gave me a example or url ? let me understand what is they do ,how can i call they ?
I want to use filters, How shall I put it?.
https://jp.vuejs.org/examples/
<pre prop-innerHTML={ marked('# hello') }>
Can't seem to get domPropsInnerHTML
to work. When using createElement
directly it works as expected.
See http://www.webpackbin.com/41TjHAOIM (the App.js tab). You can uncomment the first return (the one using h
) to see it working.
JSX <UpperCamelCased/>
strings are passed to h
as an identifier, I did not find documentation about working with Components
, by converting everything to a string we can use PascalCase component names to replace existing tags, like button
.
My proposed solution is <\Button></Button>
<\button></button>
escaping the name makes all tags identifiers.
Why there is not a babel plugin which can transform '.vue' file at runtime at server-side?
This jsx plugin is more like react-style, client side code is not easy to transport to server-side.
<compo on-event-name={ this.handlerEvent } />
console
SyntaxError: Unexpected token (68:17)
const Component = {....}
.....
<Component></Component>
eslint complains that Component
is never used.
I tried adding
"parserOptions": {
"ecmaFeatures": {
"jsx": true
}
},
to .eclintrc.js, but that didn't seem to help.
I'm playing around with the new vue 2.0 features and loving thus far!
I'm having a hard time importing JSX templates from files.
I'm following this example:
https://github.com/chrisvfritz/vue-2.0-simple-routing-example
export default ( h ) => {
<this.RouteComponent></this.RouteComponent>
}
import Vue from 'vue'
import Root from './routes/root/root.vue'
import Login from './routes/login/login.vue'
import About from './routes/about/about.vue'
import jsxfile from './main.jsx'
const Routes = {
'login': Login,
'about': About,
}
const App = new Vue( {
el: '#app',
data: {
route: {
name: '',
query: {},
},
},
computed: {
RouteComponent() {
return Routes[ this.route.name ] || Login
}
},
created: function () {
this.hashchange( window.location.hash )
window.addEventListener( 'hashchange', this.hashchange )
},
methods: {
hashchange: function () {
},
routergo: function ( route ) {
},
},
render: jsxfile, // cant seem to get 'this' scope to carry over
render: function ( h ) { // neither of these seem to be working :/
return jsxfile( h )
},
} )
I'd like to carry over the this
scope from the vue instance so inside my JSX I can use this.RouteComponent
.
Any thoughts on how to get this working? Thank you!!!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.