React进修笔记1:环境搭建

新搭建的个人博客,本文地点: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'
    }

尝试修正src/index.js的内容,页面有自动革新了

OK,到此完成环境的基础搭建!

    原文作者:StonePanda
    原文地址: https://segmentfault.com/a/1190000004336904
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞