Typescript 内置的模块导入兼容方式

2020-6-4    seo达人

一、前言

前端的模块化规范包括 commonJS、AMD、CMD 和 ES6。其中 AMD 和 CMD 可以说是过渡期的产物,目前较为常见的是commonJS 和 ES6。在 TS 中这两种模块化方案的混用,往往会出现一些意想不到的问题。


二、import * as

考虑到兼容性,我们一般会将代码编译为 es5 标准,于是 tsconfig.json 会有以下配置:


{

 "compilerOptions": {

   "module": "commonjs",

   "target": "es5",

 }

}

代码编译后最终会以 commonJS 的形式输出。

使用 React 的时候,这种写法 import React from "react" 会收到一个莫名其妙的报错:


Module "react" has no default export

这时候你只能把代码改成这样:import * as React from "react"。

究其原因,React 是以 commonJS 的规范导出的,而 import React from "react" 这种写法会去找 React 模块中的 exports.default,而 React 并没有导出这个属性,于是就报了如上错误。而 import * as React 的写法会取 module.exports 中的值,这样使用起来就不会有任何问题。我们来看看 React 模块导出的代码到底是怎样的(精简过):


...

var React = {

 Children: {

   map: mapChildren,

   forEach: forEachChildren,

   count: countChildren,

   toArray: toArray,

   only: onlyChild

 },


 createRef: createRef,

 Component: Component,

 PureComponent: PureComponent,

 ...

}


module.exports = React;

可以看到,React 导出的是一个对象,自然也不会有 default 属性。


二、esModuleInterop

为了兼容这种这种情况,TS 提供了配置项 esModuleInterop 和 allowSyntheticDefaultImports,加上后就不会有报错了:


{

 "compilerOptions": {

   "module": "commonjs",

   "target": "es5",

   "allowSyntheticDefaultImports": true,

   "esModuleInterop": true

 }

}

其中 allowSyntheticDefaultImports 这个字段的作用只是在静态类型检查时,把 import 没有 exports.default 的报错忽略掉。

而 esModuleInterop 会真正的在编译的过程中生成兼容代码,使模块能正确的导入。还是开始的代码:


import React from "react";

现在 TS 编译后是这样的:


var __importDefault = (this && this.__importDefault) || function (mod) {

   return (mod && mod.__esModule) ? mod : { "default": mod };

};


Object.defineProperty(exports, "__esModule", { value: true });


var react_1 = __importDefault(require("react"));

编译器帮我们生成了一个新的对象,将模块赋值给它的 default 属性,运行时就不会报错了。


三、Tree Shaking

如果把 TS 按照 ES6 规范编译,就不需要加上 esModuleInterop,只需要 allowSyntheticDefaultImports,防止静态类型检查时报错。


{

 "compilerOptions": {

   "module": "es6",

   "target": "es6",

   "allowSyntheticDefaultImports": true

 }

}

什么情况下我们会考虑导出成 ES6 规范呢?多数情况是为了使用 webpack 的 tree shaking 特性,因为它只对 ES6 的代码生效。


顺便再发散一下,讲讲 babel-plugin-component。


import { Button, Select } from 'element-ui'

上面的代码经过编译后,是下面这样的:


var a = require('element-ui');

var Button = a.Button;

var Select = a.Select;

var a = require('element-ui') 会引入整个组件库,即使只用了其中的 2 个组件。

babel-plugin-component 的作用是将代码做如下转换:


// 转换前

import { Button, Select } from 'element-ui'

// 转换后

import Button from 'element-ui/lib/button'

import Select from 'element-ui/lib/select'

最终编译出来是这个样子,只会加载用到的组件:


var Button = require('element-ui/lib/button');

var Select = require('element-ui/lib/select');

四、总结

本文讲解了 TypeScript 是如何导入不同模块标准打包的代码的。无论你导入的是 commonJS 还是 ES6 的代码,万无一失的方式是把 esModuleInterop 和 allowSyntheticDefaultImports 都配置上。

分享本文至:

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档