您的位置:首页 > Web前端 > React

一步一步使用webpack创建react项目

2017-09-25 17:27 826 查看
写在前面的话

2016年6月首次接触到react.js,由于某些原因,对react其实不是很了解。当时对webpack的使用也知之甚少,根本不会搭建react项目。最近,由于一个项目使用到react.js,花了点时间,自己搭建了一个react的项目。将步骤记录于此,以免忘记。

项目目录结构:



创建项目步骤:

安装依赖包:

1. 首先确定已安装node.js

2. 使用命令行进入
F:\nodeSpace\dev
,输入
mkdir plan-app
并进入
plan-app
目录下;

3. 在命令行中输入
npm init
,然后一直回车直到提示输入yes或no,并输入yes;

4. 安装webpack相关的插件,输入
npm install --save webpack webpack-dev-server html-webpack-plugin
;

6. 安装babel相关的插件,输入
npm install --save babel-loader babel-core babel-preset-es2015 babel-preset-react babel-preset-stage-0
;

7. 安装css样式和图片导入插件,输入
npm install --save css-loader style-loader url-loader file-loader
;

8. 安装react,输入
npm install --save react react-dom
;

到此,react项目的依赖包基本安装完毕。当然完整项目你还必须安装路由以及其他你要用到的插件,如:redux,antd等,这里只介绍到可以在页面显示“hello react”;

接下来时配置webpack的配置文件:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = (env,args)=>{
return {
context:path.resolve(__dirname,'src'),
entry:()=>path.resolve(__dirname,'src/index.jsx'),
output:{
filename:'bundle.[hash].js',
path:path.resolve(__dirname,'src/dist'),
publicPath:'/'
},
module:{
rules:[{
test:/\.jsx?$/,
include:[path.resolve(__dirname,'src')],
exclude:[path.resolve(__dirname,'node_modules')],
enforce:'pre',
use:[{
loader:'babel-loader',
options:{
presets:['es2015','react','stage-0']
}
}]
},{
test:/\.css$/,
use:[{
loader:'style-loader'
},{
loader:'css-loader'
}]
},{
test:/\.(jpg|gif|png)/,
use:[{
loader:'url-loader',
options:{
limits:3400
}
}]
}]
},
resolve:{
modules : [path.resolve(__dirname,'node_modules'),path.resolve(__dirname,'src')],
extensions:['.js','.json','.jsx']
},
devtool : "eval-source-map",
devServer:{
hot : true,
contentBase:path.join(__dirname,'src'),
compress:true,
historyApiFallback:true,
inline :true
},
plugins:[
new HtmlWebpackPlugin({
hot: true,
lazy: true,
inject:'body',
hash:true,
template: path.resolve(__dirname,"src/index.html")
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
]
}
}


然后在src目录下创建index.jsx和index.html

//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>redux demo</title>
</head>
<body>
<div id="content"></div>
</body>
</html>


import React from  'react';
import ReactDOM from 'react-dom';
const App = ()=>(<div>
<h3>hello react</h3>
</div>);

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


至此,整个demo完成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webpack react