React里面有一个规范:
Note:
The comment parser is very strict right now; in order for it to pick up the@jsx
modifier,two conditions are required.
The@jsx
comment block must be the first comment on the file.
The comment must start with/**
(/*
and//
will not work).
If the parser can't find the@jsx
comment,it will output the file without transforming it.
实例:
/** @jsx React.DOM */ React.renderComponent( React.DOM.h1(null,'Hello,world!'),document.getElementById('example') );
出于好奇,看了一下实现,还真是有点收获:
facebook有一个JSXTransformer.js的工具,做一些js的parse工作
var docblock = require('jstransform/src/docblock');
这个jstransform哪里有呢?
这个东西可以做很多事情,看了一下源码
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/; var ltrimRe = /^\s*/; /** * @param {String} contents * @return {String} */ function extract(contents) { var match = contents.match(docblockRe); //match == > ["/** @jsx React.DOM */","/** @jsx React.DOM */"," "] if (match) { //这部分是去掉开始的空格 //比如 /** @jsx React.DOM */这种会过滤前面的空格 return match[0].replace(ltrimRe,'') || ''; } return ''; }
function parseAsObject(docblock) { var pairs = parse(docblock); //pairs ==> [["jsx","React.DOM"]] var result = {}; for (var i = 0; i < pairs.length; i++) { result[pairs[i][0]] = pairs[i][1]; } return result; }