本篇是前文的扩展延伸。
美化webpack输出信息
webpack在开发时的输出信息有一大堆,可能会干扰我们查看信息,以下提供一个美化、精简输出信息的建议。
精简以下开发服务器输出信息,修改webpack.dev.js
:
1 2 3 4 5 6 7 8 9 10 11 12
| stats: { colors: true, children: false, chunks: false, chunkModules: false, modules: false, builtAt: false, entrypoints: false, assets: false, version: false }
|
美化一下打包输出,安装依赖:
修改config/build.js
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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'); });
|
分别运行打包和开发命令,控制台界面是不是清爽多了?
路由的配置
本段提供一个react-router
的实践。
安装依赖:
1 2
| $ npm i react-router-dom react-router-config @types/react-router-dom @types/react-router-config $ npm i @loadable/component
|
新建src/router.ts
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import loadable from '@loadable/component';
export const basename = '';
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' }, { path: '*', exact: true, component: loadable(() => import('@/pages/demo/404Page/404Page')), name: '404', title: '404' } ];
|
改造index.tsc
,启用路由:
1 2 3 4 5 6 7 8 9 10 11
| 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:
1 2 3 4 5 6 7 8 9 10 11
| import { useEffect } from 'react';
export function useDocTitle(title: string) { useEffect(() => { const originalTitle = document.title; document.title = title; return () => { document.title = originalTitle; }; }); }
|
把hook应用在需要修改标题的组件中即可:
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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;
|