安裝NPM和Node.js
安裝完以后就會有最新版的Node.js和NPM
創(chuàng)建App目錄
npm init
生成的package.json 里,** scripts** 最重要,這里定義的參數(shù)會在** npm run **的時候進行調用。
具體指南:阮一峰——npm scripts使用指南
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --devtool eval-source-map --progress --host 192.168.20.6 --colors --hot --content-base ./build --module-bind 'css=style!css' "
},
- --host 192.168.20.6 ,用于 webpack server 時所用的地址
- --hot 熱更新
安裝webpack
app根目錄下創(chuàng)建 webpack.config.js
npm install webpack --save-dev
--save-dev 保存到當前文件夾
webpack作用
- 打包應用
- 打包壓縮靜態(tài)文件(css,jsx)
- 熱更新
安裝 webpack-dev-server 熱更新服務器
npm install --save-dev webpack-dev-server
它將在當前文件夾下啟動一個websocket服務,端口號為8080
在package.json里我們只需要添加,這一段東西 (script有了,其實這一步沒必要)
devServer: {
port: 8080 //設置監(jiān)聽端口(默認的就是8080)
contentBase: "./build",//本地服務器所加載的頁面所在的目錄
colors: true,//終端中輸出結果為彩色
historyApiFallback: true,//不跳轉,用于開發(fā)單頁面應用,依賴于HTML5 history API 設置為true點擊鏈接還是指向index.html
}
安裝React最新版本
npm install --save-dev react react-dom
安裝Babel
npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-2
專門用來熱更新 React的react-hot-loader(最新版本)
npm install --save react-hot-loader@next
最重要的:新建.babelrc
并配置
// 新建.babelrc
{
"presets": [
["es2015", {"modules": false}],
// webpack現(xiàn)在已經支持原生的import語句了, 并且將其運用在tree-shaking特性上
"stage-2",
// 規(guī)定JS運用的語言規(guī)范層級
// Stage 2 是 "草案", 4 是 "已完成", 0 is "稻草人(strawman)"。
// 詳情查看 https://tc39.github.io/process-document/
"react"
// 轉譯React組件為JS代碼
],
"plugins": [
"react-hot-loader/babel"
// 開啟react代碼的模塊熱替換(HMR)
]
}
最終webpack.config.js
配置
const { resolve } = require('path');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: [
'react-hot-loader/patch',
'webpack/hot/only-dev-server',
'./app/main.js'
],
output: {
path: resolve(__dirname, 'build'),//打包后的文件存放的地方
filename: "bundle.js",//打包后輸出文件的文件名
publicPath: "/"
},
devServer: {
contentBase: resolve(__dirname, 'build'),
hot: true,
publicPath: '/',
},
module: {
rules: [
{
test: /\.jsx?$/,
use: [
'babel-loader',
],
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader','css-loader'
],
exclude: /node_modules/
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
],
devtool: "cheap-eval-source-map",
};
最終文件目錄
最終的文件目錄結構,以后可以寫個python腳本自動配置環(huán)境,奶奶的氣死老子
寫main.js內容
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import Cpt from './component';
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Component />
</AppContainer>,
document.getElementById('div1')
)
};
render(Cpt);
if(module.hot) {
module.hot.accept( () => {
render(Cpt)
});
}
寫component.js
import React from 'react';
const Cpt = () => (
<div>
<h1>我是蓋世英雄!</h1>
</div>
);
export default Cpt;
最后
npm run dev
筆記來源和總結
- 寫個腳本可以一件配置
- es6的react教程不多,不全,要看都看es6的。
-
module.hot.accept()
這個函數(shù)的api改了,只有一個參數(shù),是一個function