webpack+react搭建环境

近日自己项目遇到需要用webpack搭建react环境,查了挺多 ,自己总结一下

1.下载安装最新版node.js(https://nodejs.org/en/

2.主要看自己网络情况,可以选择安装淘宝镜像去搭建环境

npm config set registry http://registry.npm.taobao.org/

3.通过npm/cnpm全局安装webpack, Babel, Webpack-dev-server:

npm install babel webpack webpack-dev-server -g

4.选择项目存放目录,用npm init 初始化 npm 项目

5.在项目中安装 react, react-dom

npm install react react-dom --save

6.在项目中安装 Babel 转换器,这里用到插件 babel-preset-react, babel-preset-latest,latest 即最新的 ES 规范,包括了 Async/Await 这些新特性。

npm install babel-loader babel-core babel-preset-react babel-preset-latest --save

7.创建项目文件,main.js 即项目入口文件,App.js 即 React 组件主文件

文件目录最终为:

8.配置webpack,编辑webpack.config.js

module.exports = {
    entry: './main.js', // 入口文件路径
    output: {
        path: '/',
        filename: 'index.js'
    },
    devServer: {
        inline: true,
        port: 3333
    },
    module: {
        loaders: [
            {
                test: /\.js$/, // babel 转换为兼容性的 js
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'latest']
                }
            }
        ]
    }
}

9.写index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>React Hello World</title>
</head>
<body>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>

写App.js:

import React from 'react';

class App extends React.Component {

    render() {
        return <div>Hello World!</div>
    }
}

export default App

写Main.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('app'));

10.配置 npm scripts, 编辑 package.json,在"scripts"属性处添加一行:

"scripts": {
   "start": "webpack-dev-server"
},

11.基本的框架搭建完毕,npm start 然后打开 http://localhost:3333 试试:

npm start

posted @ 2017-08-17 16:57  张正-博客园  阅读(374)  评论(0编辑  收藏  举报