当前位置:首页 » 其他

react+babel+webpack初试

2015-12-28 16:49 本站整理 浏览(4)
  在上一篇,我们简单学习了webpack学习,现在这里我们简单学习一下react+babel+webpack,进行编译react语法jsx以及结合es6写法。
  这里我就简单的直接上demo:
  package.json文件:
{
  "name": "react-sample",
  "version": "1.0.0",
  "description": "webpack demo",
  "main": "./src/entry.js",
  "scripts": {
    "build": "webpack --display-error-details"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/dwqs/react_practice.git"
  },
  "keywords": [
    "react",
    "webpack"
  ],
  "author": "pomy",
  "devDependencies": {
    "react": "^0.13.3",
    "webpack": "^1.12.2",
    "babel-core": "^5.8.25",
    "babel-loader": "^5.3.2"
  }
}

  webpack.config.js配置文件:
var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, './src/entry.js'),
    output: {
        path: path.resolve(__dirname, './assets'),
        filename: 'bundle.js'
    },

    module: {
        //加载器配置
        loaders: [
            { test: /\.js?$/, loaders: ['babel'], exclude: /node_modules/ },
            { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/}
        ]
    },

    resolve:{
        //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名
        extensions:['','.js','.json']
    },
};

  entry.js入口文件:
import React from 'react';
import { render } from 'react-dom';
//import Hello from './hello';

var HelloMessage = React.createClass({
render: function() {
  return <h1>Hello {this.props.name}</h1>;
}
});

render(
<HelloMessage name="John" />,
document.getElementById('example')
);

  index.js:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Sample</title>
</head>
<body>
 <div id="example"></div>
<script src="./assets/bundle.js"></script>
</body>
</html>

   当我们文件夹有以上文件时,我们就可以执行,npm install (简写npm i)以及npm build 就可以编译es6写的jsx文件,打开页面就可以看到效果了。
相关资料来源:
  react-dom
  详解前端模块化工具-Webpack
  ECMAScript 6 介绍