本文为简单搭建一个react的初始开发环境。
1.工程目录
新建一个工程目录(比如react-demo),在window中cmd控制台进入该目录下,执行npm init初始化目录,如下
在工程目录下新建文件夹src用来存放源文件,新建文件夹dist用来存放打包后的文件,在src内新建文件夹component用来存放组件,新建文件index.js表示打包的入口文件,在根目录下新建webpack.config.js作为webpack的配置文件.如下:
2.安装webpack
局部安装
npm install webpack --save-dev在webpack.config.js中加入以下配置:
var path = require('path'); module.exports = { entry: { app: "./src/index.js" },output: { path: path.resolve(__dirname,'dist'),filename: '[name].bundle.js' } }
3.在package.json中添加命令
在包文件中的script中添加一条命令,然后在控制台输入npm run dev执行打包命令:
{ "name": "react-demo","version": "1.0.0","description": "","main": "index.js","scripts": { "test": "echo \"Error: no test specified\" && exit 1","dev": "./node_modules/.bin/webpack" //执行webpack命令 },"author": "","license": "ISC","devDependencies": { "webpack": "^2.5.1" } }
4.支持es6和react
项目安装babel,如下
npm install babel-loader babel-core babel-preset-es2015 --save项目安装react,如下:
npm install react react-dom babel-preset-react --save
在webpack加入配置:
var path = require('path'); module.exports = { entry: { app: "./src/index.js" },filename: '[name].bundle.js' },module: { rules: [ { test: /\.jsx?$/,exclude: path.resolve(__dirname,'/node_modules/'),loader: 'babel-loader',options: { presets: ['es2015','react'] } } ] },// 在import的时候可以省略文件名后缀 resolve: { extensions: ['.js','.jsx','.json','.conffee'] } }在入口文件index.js中写入以下代码:
import React from 'react'; import ReactDOM from 'react-dom'; class IndexComponent extends React.Component{ render() { return <h1>hello world!</h1> } } var dom = document.getElementById('app'); ReactDOM.render( <IndexComponent />,dom )在dist目录下新建一个index.html,插入打包后的js文件,如下:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width,initial-scale=1.0"> <Meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"></div> <script src="./app.bundle.js"></script> </body> </html>在浏览器打开,f12审查元素:
另外组件在写css时候可能要用到css-loader等一系列加载器,我们这不累赘。
5.安装webpack服务器
安装webpack-server-dev,如下:
npm install webpack-server-dev --save修改package.json文件下的dev命令为:
"dev": "./node_modules/.bin/webpack-dev-server --content-base dist"运行npm run dev,在浏览器中输入localhost:8080查看结果