React+es6+react-router-dom 环境配置

原创 13533613144 随笔 React 78阅读 2018-08-17 14:58:15 举报

配置前提要先安装好node,npm。

以下是一个练习的demo安装

项目目录如下

1.新建文件并创建package.json
mkdir react-demo
cd react-demo
npm init(注意填写信息时,entry point 用默认的index.js 不要修改)

2.安装
//安装 react reactDOM 插件
npm install react react-dom --save

//安装webpack所需的配置
npm install webpack webpack-dev-server --save
npm install webpack webpack-cli path html-webpack-plugin --save-dev

//安装转码编译babel

npm install babel babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-3 --save-dev

//安装路由
npm install react-router-dom

//安装其他配置
npm install css-loader sass-loader style-loader node-sass prop-types --save-dev

然后复制下面把他们放在package.json的script 里边(如图所示),放好之后在react-demo(当前项目的文件夹执行 npm install 安装)

"build": "npm run clean && webpack --progress --colors --bail",
"dev": "webpack-dev-server --hot --inline --port 9000 --open",
"clean": "rimraf ./build && mkdirp build"

3.配置webpack.config.js文件
(新建一个webpack.config.js,把以下复制进入就大功告成啦!)

var path = require('path');
var webpack = require('webpack');
var htmlWebpackPlugin = require('html-webpack-plugin');

var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'src');
var BUILD_PATH =path.resolve(ROOT_PATH, 'build');

module.exports = {
entry: path.resolve(APP_PATH, 'index.jsx'),
output: {
path: BUILD_PATH,
filename: 'bundle.js'
},
module: {
rules:[
{
test: /.(less|scss|css)$/,
loaders: ['css-loader', 'sass-loader']
},
{
test: /.jsx?$/,
loader:['babel-loader'],
include: APP_PATH
},
{
test: /.js$/,//不解析node_modules文件夹下的js
loader: 'babel-loader',
exclude: '/node_modules/'
}
]
},
devtool: 'eval-source-map',
devServer: {
compress: true,//启用Gzip压缩
historyApiFallback: true,//为404页启用多个路径
hot: true,//热更新
https: false,//适用于ssl安全证书网站
noInfo: true//只在热加载错误和警告
},
plugins:[
new htmlWebpackPlugin({
title: 'demo',
template: './index.html'
})
]
}

4.其他配置

4.1新建一个index.html

4.2 新建一个.babelrc文件

{
"presets": ["es2015","react","stage-3"]
}

4.3新建src文件放置项目
并在里边新建index.jsx文件

import React from 'react';
import ReactDOM from 'react-dom';
//引入路由
import {HashRouter,Route} from 'react-router-dom';

import Login from './routers/Login/index.jsx';

ReactDOM.render(
<HashRouter>
<Route path="/" component={Login}></Route>
</HashRouter>,
document.getElementById('root')
);
在index.jsx文件同级新建一个routers文件夹

并在里边新建
Login >container >index.jsx

index.jsx内容如下
import React from 'react';
import PropTypes from 'prop-types';

class LoginComponent extends React.Component{
constructor(props){
super(props);
this.state ={

    }
}
componentWillMount(){

}
render(){
    return (
        <h1>Hello, world!</h1>
    );
};

}

LoginComponent.PropTypes = {

}

export default LoginComponent;

Login > index.jsx

内容如下

import Login from './container/index.jsx'
export default Login

最后执行 npm run dev

评论 ( 1 )
最新评论
hugeannex 2018-08-17 16:42:31 1F

其实就一条命令
create-react-app xx