安装 node.js
安装 package.json文件
(npm init -y)
安装后的package.json
{ "name": "c_react","version": "1.0.0","description": "","main": "index.js","scripts": { "test": "echo \"Error: no test specified\" && exit 1" },"keywords": [],"author": "","license": "ISC","devDependencies": { "jspm": "^0.16.53" },
安装webpack (模块打包机)
npm install webpack -gd(全局安装) npm install webpack --save-dev(局部安装)
安装babel
npm install --save-dev babel-loader babel-core//这个比较慢 或 npm install cnpm -gd cnpm install --save-dev babel-loader babel-core//可以选择安装这个
安装转移的插件
npm install babel-preset-env babel-preset-react --save-dev
进入webpack官网
在自己的项目目录下建: app.js import bar from './bar'; bar(); // bar.js export default function bar() { } // webpack.config.js module.exports = { entry: './app.js',output: { filename: 'bundle.js' } }
安装 react相关库
npm install react react-dom --save
运行webpack --watch
webpack-dev-server//提供的一个服务 npm install webpack-dev-server -gd npm install webpack-dev-server --save-dev
运行 webpack-dev-server --content-base build/
自动刷新(automatic refresh)
webpack-dev-server --content-base build/ --inline
热更新 (hot replacement)
cnpm install react-hot-loader --save-dev
webpack-dev-server --content-base build/ --hot
处理样式
cnpm install style-loader css-loader --save-dev
优化项目结构
上面都是需要安装的命令,和配置的文件
接下来看完整的代码
webpack.config.js
var path=require("path"); module.exports = { devtool:'source-map',entry: './app.js',output: { path:path.resolve(__dirname,"build"),publicPath:"/assets/",filename:"bundle.js" },module: { rules: [ { test: /\.js$/,exclude: /node_modules/,loader: "react-hot-loader!babel-loader" },{ test: /\.css$/,loader: "style-loader!css-loader" } ] } }
package.json
{ "name": "c_react","scripts": { "test": "echo \"Error: no test specified\" && exit 1","start":"webpack-dev-server --content-base build/ --hot" },"devDependencies": { "babel-core": "^6.25.0","babel-loader": "^7.1.1","babel-preset-env": "^1.6.0","babel-preset-react": "^6.24.1","css-loader": "^0.28.4","react-hot-loader": "^1.3.1","style-loader": "^0.18.2","webpack": "^3.4.0","webpack-dev-server": "^2.6.1" },"dependencies": { "react": "^15.6.1","react-dom": "^15.6.1" } }
app.js
import React from 'react'; import ReactDOM from 'react-dom'; import HelloWorld from './components/HelloWorld'; import './css/main.css'; ReactDOM.render(<HelloWorld/>,document.getElementById("app"));
HelloWorld.js
import React from 'react'; class HelloWorld extends React.Component{ render(){ return( <div>hello world1</div> ); }; } //export {HelloWorld as default}; export default HelloWorld;
index.html
<!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>react环境的搭建2</title> </head> <body> <div id="app"></div> <input type="text"> <script src="assets/bundle.js"> </script> </body> </html>
这就是完整的一个环境
这是我的目录图