之前說完從零開始配置TypeScript + React + React-Router + Redux + Webpack開發環境
現在我們來看看如何根據在這個環境的基礎上配置按需加載。如果Redux也沒有關系,有React-Router就足夠了。
本來以為React的按需打包已經有很成熟的方案了,但是沒想到網上還是沒有一個基於typescript的教程,這讓typescript開發者情何以堪。
首先放棄使用require.ensure,因為@types/node中沒有定義require的ensure,就算重寫了node的index.d.ts,也會報一個warning,並且不會起作用(可能是我寫錯了,但是我按別人的教程來寫確實沒有作用)。
然后放棄使用es6的import,因為我的項目內集成了antd,如果使用import的話,必須在tsconfig.js中設置models:'commonjs',但是我antd使用按需加載必須使用models:'es2015',並且也還是不能使用(同上)。
所以這里我們采用bundle-loader,並且這篇教程不會介紹bundle的一些使用方式,因為我自己也沒摸很透。
安裝依賴
npm i -D bundle-loader@0.5.5
修改routes.tsx中的代碼
import * as React from 'react'; import { Route, IndexRoute } from 'react-router'; import * as Hello from './containers/Hello'; function lazyLoadComponent(lazyModule: any): any { return (location: any, cb: any) => { lazyModule((module: any) => cb(null, module.default)); } } export default ( <Route path="/"> <IndexRoute getComponent={lazyLoadComponent(Hello)} /> <Route path="/demo"> <IndexRoute getComponent={lazyLoadComponent(Hello)} /> </Route> </Route> );
其中Hello容器需要通過 * as 的方式引入,不然在編譯好的代碼中報錯。
chunkFilename: '[name].[chunkhash:5].chunk.js'
然后在module中添加如下規則
{ test: /src\/containers(\/.*).(tsx|ts)/, loader: "bundle-loader?lazy!ts-loader" }
我這里是用的ts-loader,你也可以改成babel-loader,都行。
注意test中匹配的是你在routes.tsx中引入的那個文件夾,一般來說都是containers。
然后運行webpack或者webpack-dev-server
可以看到我們多出來了一個chunk文件,代表我們的引用成功了。