React 开发配置文件
1.安装包
npm init
(或者npm init -y
跳过所有问题) 新建package.json
-
常用命令:
-
npm i
是npm install
简写 -
npm i -S
是npm --save
简写 -
npm i -D
是npm i --save-dev
简写
-
-
需要安装的项目开发依赖包(--save-dev)有:
babel-core
babel-preset-es2015
babel-polyfill
-
babel-loader
: transpile React and ES6 babel-preset-react
react-hot-loader
webpack
webpack-dev-server
-
安装依赖(--save):
react
react-dom
-
安装到全局环境下的包有:
webpack
webpack-dev-server
即:
// 新建 package.json
npm init -y
// --save-dev(或 -D) 项目开发依赖包
npm i -D babel-core babel-preset-es2015 babel-polyfill babel-loader
babel-preset-react react-hot-loader webpack webpack-dev-server
// --save(或 -S) 项目依赖包
npm i -S react react-dom
// 全局(-g)下的包
npm i -g webpack webpack-dev-server
2.配置webpack.config.js
根目录下新建文件 webpack.config.js
:
const webpack = require("webpack");
const path = require("path");
module.exports = {
devtool: "inline-source-map", // 用于调试
entry: [
"webpack-dev-server/client?http://127.0.0.1:8080/",
"webpack/hot/only-dev-server",
"./src" // 'src'文件下的所用js文件
],
output: {
path: path.join(__dirname, "public"), // '__dirname'表示当前根目录路径
filename: "bundle.js" // 标准输出文件
},
// webpack 寻找所需要的文件
resolve: {
moduleDirectories: ["node_modules", "src"],
extension: ["", ".js"]
},
// 注意事项:
// 1. "loaders" 不能写成 "loader"
// 2. "babel?presets[]=react,presets[]=es2015"
// 不能写成"babel?presets[]=es2015,presets[]=react"
// 因为babel转换是有先后顺序的,从you'dao'zuo
module: {
loaders: [
{
test: /\.jsx?$/,
exculde: /node_modules/,
loaders: ["react-hot-loader/webpack", "babel?presets[]=react, presets[]es2015"]
}
]
},
plugins: {
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorPlugin() // 查看错误
}
}
3.目录结构
例如:
- react-todos
- node_modules
- src
- components
- app.js
- create-todos.js
- todos-list.js
- todos-list-header.js
- todos-list-item.js
- index.js
- components
- index.html
- webpack.config.js
- package.json
4.index.thml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React ToDos</title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
5.建立实时预览开发
-
接下来就是 书写组件(components),实时修改: 在Terminal中输入:
webpack-dev-server
-
建立本机服务器,浏览器中输入:
localhost:8080/webpack-dev-server/
配置结束
2016/9/28 11:22:14