Typescript + React-Router + Webpack 實現按需打包/加載 從零開始配置TypeScript + React + React-Router + Redux + Webp

以前說完從零開始配置TypeScript + React + React-Router + Redux + Webpack開發環境php

如今咱們來看看如何根據在這個環境的基礎上配置按需加載。若是Redux也沒有關係,有React-Router就足夠了。html

 

原本覺得React的按需打包已經有很成熟的方案了,可是沒想到網上仍是沒有一個基於typescript的教程,這讓typescript開發者情何以堪。node

首先放棄使用require.ensure,由於@types/node中沒有定義require的ensure,就算重寫了node的index.d.ts,也會報一個warning,而且不會起做用(多是我寫錯了,可是我按別人的教程來寫確實沒有做用)。react

而後放棄使用es6的import,由於個人項目內集成了antd,若是使用import的話,必須在tsconfig.js中設置models:'commonjs',可是我antd使用按需加載必須使用models:'es2015',而且也仍是不能使用(同上)。webpack

 

因此這裏咱們採用bundle-loader,而且這篇教程不會介紹bundle的一些使用方式,由於我本身也沒摸很透。git

安裝依賴es6

npm i -D bundle-loader@0.5.5

修改routes.tsx中的代碼github

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 的方式引入,否則在編譯好的代碼中報錯。web

而後以前toute上的component須要替換爲getComponent,這是官方提供的按需加載的方法。
 
代碼修改完畢,咱們接下來須要修改webpack中的output,在output屬性中添加以下一條
chunkFilename: '[name].[chunkhash:5].chunk.js'

而後在module中添加以下規則typescript

{ test: /src\/containers(\/.*).(tsx|ts)/, loader: "bundle-loader?lazy!ts-loader" }

我這裏是用的ts-loader,你也能夠改爲babel-loader,都行。

注意test中匹配的是你在routes.tsx中引入的那個文件夾,通常來講都是containers。

 

而後運行webpack或者webpack-dev-server

能夠看到咱們多出來了一個chunk文件,表明咱們的引用成功了。

相關文章
相關標籤/搜索