使用webpack构建一个react demo

第一步

创建一个项目目录,由于demo比较简单所以所有文件在同一个目录

然后在命令行cd到项目目录,使用npm init 一路回车得到一个package.json文件这个是包管理的配置文件。

其中bundle.js是webpack打包后的文件,webpack.config.js是webpack的配置文件,webpack.config.js、index.html、index.js这三个文件手动创建

第二步

安装所依赖的包, 如下:

{
  "name": "yes",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel": "^6.23.0",
    "babel-loader": "^6.4.0",
    "babel-plugin-react-html-attrs": "^2.0.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "babelify": "^7.3.0",
    "react": "^15.5.4",
    "react-dom": "^15.4.2",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.5"
  }
}

 

 dependencies这个是配置依赖的包,其中babel是对es6语法的解析,react和react-dom是react框架的包,webpack和webpack-dev-server是打包工具以及起一个最小的服务。

第三步

代码以及配置文件的编写

index.html文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>reactDemo</title>
</head>
<body>
  <div id="mainContainer"></div>
</body>
<script src="bundle.js"></script>
</html>

index.js 文件如下:

import React from 'react';
import ReactDOM from 'react-dom';

export default class Root extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      inputContent:''
    }
  }

  handlerChange(event) {
    this.setState({
      inputContent: event.target.value
    })

    event.preventDefault()
    event.stopPropagation()
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handlerChange.bind(this)}/><span>{this.state.inputContent}</span>
      </div>
    )
  }
}

ReactDOM.render(
  <Root/>,
  document.getElementById('mainContainer')
)

webpack.config.js 文件如下:

var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: __dirname,
  entry: './index.js',
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015'],
        }  
      },
    ]
  },
  output: {
    path: __dirname,
    filename: "bundle.js"
  },
};

到此项目代码编写完毕,我们打开命令行cd到项目目录,输入  webpack-dev-server 出现如下提示说明你的项目已经跑起来了

打开浏览器访问: http://localhost:8080/  

有关webpack和webpack-dev-server的配置文件更多信息 --> https://webpack.js.org/configuration/

posted @ 2017-05-05 11:22  slardarr  阅读(165)  评论(0编辑  收藏  举报