webpack搭建React环境
2017-11-03 本文已影响0人
xiangbei10hao
环境准备
1.安装nodejs、npm
访问网站http://nodejs.cn/download/下载需要的版本的nodejs
下载后直接点击安装,然后cmd执行node -v和npm -v
出现上图内容则安装完成,如果没有需要配置环境变量(一般都会自动配置环境变量的)
2.创建react工程目录
创建react_demo的文件目录,并创建文件如下:
- package.json:
{
"name": "react_demo",
"version": "0.0.1",
"description": "",
"main": "",
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server --hot --inline --host 0.0.0.0 --port 8080"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-core": "^6.17.0",
"babel-eslint": "^7.2.1",
"babel-loader": "^6.2.5",
"babel-plugin-import": "^1.1.1",
"babel-preset-es2015": "^6.16.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-0": "^6.24.1",
"eslint": "^3.19.0",
"eslint-config-airbnb": "^14.1.0",
"eslint-import-resolver-webpack": "^0.8.1",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.10.3",
"webpack": "^2.2.1",
"webpack-dev-server": "^1.16.2"
}
}
- webpack.config.js
const path = require('path')
var webpack = require('webpack');
const root = __dirname;
module.exports = {
// 入口文件
entry: path.resolve(root, 'src/index.jsx'),
// 出口文件
output: {
filename: 'bundle.js',
path: path.resolve(root, 'build')
},
resolve: {
extensions: ['*', '.js', '.jsx'] //webpack2.x extensions[0]不能为空
},
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
disableHostCheck: true
},
module: {
loaders: [
{
test: /(\.js|\.jsx)$/,
loaders: [
'babel-loader'
],
exclude: /node_modules/,
}
],
}
}
- .babelrc
{
"presets" : [ "react", "es2015"]
}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Demo</title>
</head>
<body>
<div id="app"></div>
<script src="build/bundle.js"></script>
</body>
</html>
- index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Root from './components/Root';
ReactDOM.render(
<Root />,
document.getElementById('root')
);
- Root.jsx
import React from 'react';
class Root extends React.PureComponent{
render() {
return (
<h1> Hello World!</h1>
);
}
}
export default Root;
- 执行配置
-
执行依赖包安装
在项目根目录下,执行npm install:
执行后的文件目录,生成node_modules目录和package-lock.json文件:
-
执行webpack配置
在项目根目录下,执行npm run build:
执行后的文件目录,生成build目录,build目录下生成bundle.js文件:
- 运行服务
-
启动服务
根目录下执行npm run start:
-
访问服务
浏览器中输入localhost:8080
大功告成