1. 程式人生 > >一步一步進入React的世界(React+Webpack+ES6組合配置)

一步一步進入React的世界(React+Webpack+ES6組合配置)

看了很多部落格,大都是把配置檔案一筆帶過,或者乾脆不給出配置檔案,然而環境搭建對於新手來說是既困難又重要,顯然網路上的部落格不利於新手開始學習。
BZ打算從從頭開始,一步一步配置webpack,能夠使用ES6+React組合開發,廢話少說讓我們一起來開始Webpack+ES6+React之旅。

當然你也可以使用本博文最後總結的部分或者從我的github中獲得,全部安裝外掛npm install,然後執行webpack就可以編譯了。
- 使用命令npm init新建包管理檔案
- 在專案根目錄下新增webpack.config.js檔案,它的基本結構是:

var webpack = require
('webpack'); module.exports = { entry:{ page: "./src/app.js" }, output: { path: './build', filename: "bundle.js" }, module: { loaders: [ {test:/\.js$/,exclude: /node_modules/,loader:''},//載入器在這裡 //下面我們會在這裡增加 ] } };

1.支援es6

 npm i --save-dev babel-core babel-loader babel-preset-es2015

webpack.config.js

{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }

.babelrc

{
  "presets": [
    "es2015"
  ]
}

入口app.js,es6語法

var p = require("./es6test/es6test1.js")
//es6test1.js
import Point from './es6test2';
let p = new Point(1,2);
console.log(p.toString()); 
//es6test2.js
class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } } export default Point;

2. 支援React語法

{test:/\.jsx$/,exclude: /node_modules/,loader:'jsx-loader?harmony'}

入口檔案app.js

var React = require('react');
var ReactDOM = require('react-dom');


var HelloMessage = React.createClass({
   render: function() {
     return <h1>Hello {this.props.name}</h1>;
  }
});


ReactDOM.render( <HelloMessage name="John" />,
   document.getElementById('example')
);

3. React和es6同時支援

  • 安裝
 npm i --save-dev babel-preset-react

注意:.babelrc檔案和上面的是一樣也是必須的。
webpack.config.js

{test:/\.jsx?$/,exclude: /node_modules/,loader: 'babel', query: {presets: ['es2015', 'react']}},
//同時支援es6 react 或者下面的寫法都可以
{test:/\.jsx?$/,exclude: /node_modules/,loader:'babel?presets[]=react,presets[]=es2015'},
//同時支援es6 react

使用React,es6語法

import React from 'react';
import ReactDOM from 'react-dom';


class HelloMessage extends React.Component {
    render() {
        return <h1> Hello { this.props.name } </h1>;
    }
}
ReactDOM.render( <HelloMessage name="zry" />,
   document.getElementById('example')
);

4. 其餘配置

css/sass

  • 安裝
npm i --save-dev  style-loader  css-loader sass-loader  node-sass
  • webpack.config.js
{ test: /\.css$/, loader: "style!css" },
{ test: /\.scss$/, loader: "style!css!sass" }, //sass載入器

使用很簡單

import "./home/home.css";
import "./home/home.scss";

5. 基本功能配置總結:

package.json

{
  "name": "react-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --hot --progress --colors",
    "build": "webpack --progress --colors"
  },
  "repository": {
    "type": "git",
    "url": "zry"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.18.0",
    "babel-loader": "^6.2.7",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.25.0",
    "jsx-loader": "^0.13.2",
    "node-sass": "^3.10.1",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.3"
  }
}

webpack.config.js

var webpack = require('webpack');


module.exports = {
entry:{
page: "./src/app.js"
},
    output: {
        path: './build',
        filename: "bundle.js"
    },
    module: {
        loaders: [
            // { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },//支援es6
            // {test:/\.jsx?$/,exclude: /node_modules/,loader:'jsx-loader?harmony'},//支援react
            // {test:/\.jsx?$/,exclude: /node_modules/,loader:'babel?presets[]=react,presets[]=es2015'},//同時支援es6 react或者
            {test:/\.jsx?$/,exclude: /node_modules/,loader: 'babel', query: {presets: ['es2015', 'react']}},//同時支援es6 react
            { test: /\.css$/, loader: "style!css" },
            { test: /\.scss$/, loader: "style!css!sass" }, //sass載入器
        ]
    },
    resolve: {
        extensions: ['', '.js', '.json']
    },
    plugins: [
        new webpack.NoErrorsPlugin()
    ],
    devtool: 'source-map'
};

別忘了.babelrc檔案

{
  "presets": [
    "es2015"
  ]
}

6. React支援熱插拔

webpack-dev-server支援熱插拔(熱替換 HRM),使用HRM功能也有兩種方式:命令列方式和Node.js API 方式。

6.1 Node.js API方式

Node.js API方式需要做三個配置:
1) 把webpack/hot/dev-server加入到webpack配置檔案的entry項;
2) 把new webpack.HotModuleReplacementPlugin()加入到webpack配置檔案的plugins項;
3) 把hot:true加入到webpack-dev-server的配置項裡面。

使用 react 編寫程式碼時,能讓修改的部分自動重新整理。但這和自動重新整理網頁是不同的,因為 hot-loader 並不會重新整理網頁,而僅僅是替換你修改的部分
- 安裝

npm i --save-dev react-hot-loader webpack-dev-server
  • 修改.babelrc
{
  "presets": [
    "es2015"
  ],
  "plugins":["react-hot-loader/babel"]
}
  • 修改webpack.config.js
var webpack = require('webpack');
module.exports = {
    //修改:entry
    entry: [
        "webpack-dev-server/client?http://127.0.0.1:3000",
        "webpack/hot/only-dev-server",
        "./src/app.js"
    ],
//修改:output
    output: {
        path: __dirname,
        filename: "build/bundle.js",
        publicPath: "/build"
    },
    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } }, //同時支援es6 react
            { test: /\.css$/, loader: "style!css" },
            { test: /\.scss$/, loader: "style!css!sass" }, //sass載入器
        ]
    },
    resolve: {
        extensions: ['', '.js', '.json']
    },
    plugins: [
        new webpack.NoErrorsPlugin(), //允許錯誤不打斷程式
        new webpack.HotModuleReplacementPlugin() //增加:webpack熱替換外掛
    ],
    devtool: 'source-map'
};
  • 增加server.js檔案
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');


new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true
}).listen(3000, 'localhost', function(err, result) {
    if (err) {
        return console.log(err);
    }
    console.log('Listening at http://localhost:3000/')
});

如何使用?–在命令列中

webpack   //最好先編譯一次
node server.js  //啟動node服務

在瀏覽器輸入localhost:3000即可檢視結果,我們修改css檔案,儲存之後網頁會自動重新整理顯示在瀏覽器上。

6.2 命令列方式

命令列方式比較簡單,只需要加入--inline --hot
例子位置在我的github

這個例子中執行的命令是:

webpack-dev-server --history-api-fallback --progress --profile --inline --colors --hot --port 4000