新搭建的个人博客,本文地址:React学习笔记1:环境搭建
本文的书写环境为mac,之后会补充windows下的差异
1、创建学习目录
mkdir learn cd learn
2、npm初始化项目
npm init //根据相关提示完善信息,入口js文件:src/index.js
3、安装相关react npm包,并且使用es2015(也就是es6支持,需要babel-preset-es2015包),因为我之前做个一些js相关项目,所以部分npm包已经全局安装,比如webpack等等,大家根据提示补足自己的npm包即可
npm install --save react react-dom babel-preset-react babel-preset-es2015 babel-loader
4、创建相关文件目录结构
mkdir src //存放源文件 mkdir build //存放编译后的js文件
5、创建webpack配置文件(webpack好强大,之后再做详细的学习)
touch webpack.config.js
var path = require('path'); module.exports = { entry:[ './src/index.js' ],output: { path: path.resolve(__dirname,'build'),filename: 'bundle.js' },module: { loaders: [{ test: /\.jsx?$/,exclude: /(node_modules|bower_components)/,loader: 'babel-loader',// 'babel-loader' is also a legal name to reference query: { presets: ['es2015','react'] } }] },devServer:{ contentBase:'./build' } };
6、创建index.js源文件,书写经典的Hello World!
touch src/index.js
var React = require('react'); var ReactDOM = require('react-dom'); ReactDOM.render( <h1>Hello,world!</h1>,document.getElementById('example') );
7、利用webpack编译源文件,根目录下直接运行webpack,运行完成后会在build目录生成bundle.js文件
$ webpack Hash: 32a8e736b4323f7ec350 Version: webpack 1.12.9 Time: 1318ms Asset Size Chunks Chunk Names bundle.js 676 kB 0 [emitted] main [0] multi main 28 bytes {0} [built] + 159 hidden modules
8、创建index.html承载体文件,引入bundle.js,方便在浏览器中运行
touch build/index.html
<!DOCTYPE html> <html> <head> <Meta charset="utf-8"> <title>React环境搭建</title> </head> <body> <div id="example"></div> </body> <script src="bundle.js"></script> </html>
9、浏览器直接打开index.html,出现Hello world!
10、每次修改完成,运行webpack还是很麻烦的,利用webpack-dev-server可以完成自动自动编译,自动刷新浏览器
$ webpack-dev-server http://localhost:8080/webpack-dev-server/ webpack result is served from / content is served from ./build Hash: 67262048da84a36a0a5c Version: webpack 1.12.9 Time: 1325ms Asset Size Chunks Chunk Names bundle.js 676 kB 0 [emitted] main chunk {0} bundle.js (main) 643 kB [rendered]
浏览器进入http://localhost:8080/webpack...输出Hello world!
webpack的配置指定了webpack-dev-server的根目录
devServer:{ contentBase:'./build' }
OK,到此完成环境的基本搭建!
原文链接:https://www.f2er.com/react/307294.html