本篇是前文的擴展延伸。javascript
webpack在開發時的輸出信息有一大堆,可能會干擾咱們查看信息,如下提供一個美化、精簡輸出信息的建議。java
精簡如下開發服務器輸出信息,修改webpack.dev.js
:react
// ...webpack configs stats: { colors: true, children: false, chunks: false, chunkModules: false, modules: false, builtAt: false, entrypoints: false, assets: false, version: false }
美化一下打包輸出,安裝依賴:webpack
$ npm i -D ora chalk
修改config/build.js
:web
const ora = require('ora'); const chalk = require('chalk'); // 若是要改變輸出信息的顏色,使用這個,本例沒有用到 const webpack = require('webpack'); const webpackConfig = require('./webpack.prod'); const spinner = ora('webpack編譯開始...\n').start(); webpack(webpackConfig, function (err, stats) { if (err) { spinner.fail('編譯失敗'); console.log(err); return; } spinner.succeed('編譯結束!\n'); process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n'); });
分別運行打包和開發命令,控制檯界面是否是清爽多了?typescript
本段提供一個react-router
的實踐。npm
安裝依賴:segmentfault
$ npm i react-router-dom react-router-config @types/react-router-dom @types/react-router-config $ npm i @loadable/component
新建src/router.ts
:bash
import loadable from '@loadable/component'; // 按需加載 export const basename = ''; // 若是訪問路徑有二級目錄,則須要配置這個值,如首頁地址爲'http://tianzhen.tech/blog/home',則這裏配置爲'/blog' export const routes = [ { path: '/', exact: true, component: loadable(() => import('@/pages/demo/HelloWorldDemo/HelloWorldDemoPage')), // 組件須要你本身準備 name: 'home', // 自定義屬性 title: 'react-home' // 自定義屬性 // 這裏能夠擴展一些自定義的屬性 }, { path: '/home', exact: true, component: loadable(() => import('@/pages/demo/HelloWorldDemo/HelloWorldDemoPage')), name: 'home', title: 'HelloWorld' }, // 404 Not Found { path: '*', exact: true, component: loadable(() => import('@/pages/demo/404Page/404Page')), name: '404', title: '404' } ];
改造index.tsc
,啓用路由:服務器
import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import { renderRoutes } from 'react-router-config'; import { routes, basename } from './router'; import '@/App.less'; const App: React.FC = () => { return <BrowserRouter basename={basename}>{renderRoutes(routes)}</BrowserRouter>; }; export default App;
咱們還能夠利用路由爲每一個頁面設置標題。
先寫一個hook:
import { useEffect } from 'react'; export function useDocTitle(title: string) { useEffect(() => { const originalTitle = document.title; document.title = title; return () => { document.title = originalTitle; }; }); }
把hook應用在須要修改標題的組件中便可:
import React from 'react'; import { useDocTitle } from '@/utils/hooks/useDocTitle'; import Logo from './react-logo.svg'; import './HelloWorldDemoPage.less'; const HelloWorldDemoPage: React.FC<Routes> = (routes) => { const { route } = routes; // 獲取傳入的路由配置 useDocTitle(route.title); // 修改標題 return <div className="App">hello, world</div>; }; export default HelloWorldDemoPage;