node搭建react-router開發環境

自己搭的腳手架,因爲一些原因沒使用webpack-dev-server,目錄結構如下

|-src
    |-page1
      |-index.html
      |-index.js
      |-other.js
      |-index.scss

然後寫着寫着發現一個問題,因爲寫的是多頁面形式的工程,每個目錄下有一個html模板,又沒有實際在生產中使用,所以寫的內容比較簡單,都是自己寫一些測試的東西,但是這個結構如果要用react-router,就麻煩了,因爲針對目前這個結構,是直接使用了express的static中間件來對生成的文件進行返回,webpack打包出的文件生成在dist文件夾下面,然後啓動這樣一個node文件來監聽

const express = require("express");

const app2 = express();
const port2 = 3002;
app2.use(express.static('project/'));
app2.listen(port2);

訪問的時候,一般是輸入localhost:3002/page1.html這樣來訪問的,但是用到react-router的時候,不能直接在瀏覽器裏輸入路徑了,比如我輸入localhost:3002/page1.html/main/api,靜態文件代理就失效了,這個事情摸索了挺久,但是結果一說特別簡單,就是起兩個監聽,一個監聽html,一個監聽js和css,webpack打包的時候,給output配置一個publicPath,配置成一個和html不一樣的端口,比如html是在3003上監聽,js和css在3002上監聽,生成的html模板如下

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <div id="app"></div>
    // 注意下面這個script的src的路徑
    <script type="text/javascript" src="http://localhost:3002/dist/0708.js"></script>
  </body>
</html>

node文件如下,

const express = require("express");
const fs = require("fs");

// 監聽html
const app = express();
const port = 3003;
app.get("*", (req, res) => {
  const url = req.originalUrl;
  // 下面這行裏readFileSync的路徑可以自己改
  res.send(fs.readFileSync(`project/dist/${url.split('/')[1]}.html`).toString());
});
app.listen(port);

// 監聽js和css文件
const app2 = express();
const port2 = 3002;
app2.use(express.static('project'));
app2.listen(port2);

踩坑

這個摸索的過程裏,還遇到了一些坑,
1.react-router 3和4的不同用法

react-router 3是這樣寫的,basename是爲了上面的html文件名可以不用在route裏面寫了,注意react-router版本是3的話,history這個包的版本也要是3

import { Route, Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';

const browserHistory = useRouterHistory(createHistory)({
  basename: '/app',
});

ReactDOM.render( (
  <Router history={browserHistory}>
    <Route path="/detail1" component={DetailPage} />
    <Route path="/detail2" component={DetailPage2} />
  </Router>
), document.getElementById('root'));

react-router 4是這樣寫的,注意react-router 4要安裝的不是react-router,而是react-router-dom

import { Route, BrowserRouter } from 'react-router-dom';

const ddd = (
<BrowserRouter basename='/0708/main'>
    <Route path="/detail1" component={DetailPage} />
    <Route path="/detail2" component={DetailPage2} />
</BrowserRouter>
);

ReactDOM.render(ddd, document.getElementById("app"));

2.報錯
如果寫錯了ReactDOM.render裏面的document.getElementById的元素名稱,會報這個,但是這個錯,讓人摸不着頭腦Uncaught Invariant Violation: Minified React error #200; visit https://reactjs.org/docs/error-decoder.html?invariant=200 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.,不排除有別的情況會報這個,但是元素id寫錯了也是一種可能性

有興趣可以看看我寫的hellowebpack,相關代碼都在裏面
https://github.com/vzhufeng/helloWebpack

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章