React与ES2015(一)
ES2015(也就是ES6)带来了很多新的语言特性。比如:类、箭头方法、rest参数、promise、generator等很多。如果你对ES6还不是很熟悉的话可以看这里。 但是浏览器对于ES6的支持还不是很好。你可以看看这个ES6兼容表。显而易见的是不同浏览器对于ES6的兼容参差不齐。于是就有人想把ES6的代码转成ES5的不就可以兼容了吗。 这其中做的最好的就是Babel,一个非常棒的工具。后面会详细的介绍如何使用。 准备开发环境为了可以正常开发,那么就需要用到
下面就是 在根目录添加文件.babelrc,并在提其中添加如下内容: {
"presets": ["es2015","react"]
}
接下来配置 var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname,'src/client/public');
var APP_DIR = path.resolve(__dirname,'src/client/app');
var config = {
entry: APP_DIR + '/index.jsx',output: {
path: BUILD_DIR,filename: 'bundle.js'
},module: {
loaders: [
{
test: /.jsx?/,include: APP_DIR,loader: 'babel'
}
]
}
};
module.exports = config;
最后,在package.json文件中的 "scripts": {
"test": "echo "Error: no test specified" && exit 1","dev": "webpack -d --watch","build": "webpack -p"
},
现在可以运行命令 更多关于 JSX和Babel你可能已经注意到,我们使用的是 使用ES6写第一个React组件是不是已经等不及了。 先来看看项目结构: project
|--src
|--client
|--app
|--public
|--index.html
|--.babelrc
|--package.json
|--webpack.config.js
在app目录下创建一个文件index.jsx作为React项目的入口文件。之后添加hello-world.jsx文件。在其中添加如下代码: import React from 'react'; // 1
// 2
export default class HelloWorld extends React.Component {
// 3
render() {
// 4
return <h1>Hello from {this.props.phrase}</h1> } }
解释一下上面的代码: 组合到一起在之前已经创建好的index.js文件内添加如下内容: import React from 'react';
import {render} from 'react-dom';
import HelloWorld from './hello-world';
class App extends React.Component {
render() {
return (<div> <HelloWorld phrase="ES2015" /> </div>); } } render(<App />,document.getElementById('app'));
打开index.html文件,如果你还没有创建这个文件的话,那么创建一个。目录位置参考前面的项目目录一节。在index.html文件中添加如下内容: <html>
<head>
<meta charset="utf-8">
<title>React & ES6</title>
</head>
<body>
<div id="app" />
<script src="public/bundle.js" type="text/javascript"></script>
</body>
</html>
所需要的全部材料都有了。现在就可以用 在浏览器中打开这个html文件。你就会看到运行结果了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |