Typescript接入小程序 - 设置模块别名

3,676 阅读2分钟

现状

TS文件里, 我们任然和JS里面引用文件一样的写法引用文件

import { BaseComponent } from '../../../biz/base/index';
import XX from '../../../../dir/index';

这样写存在的问题?

  1. 手动写、拷贝路径容易出错
  2. 一旦文件位置变化,涉及文件都得改,容易改漏,而且回归成本大

Typescript里,提供了paths,能够支持使用别名(类似webapck的alias),就能解决上述问题。

具体做法

  1. 修改tsconfig.json文件如下
{
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/bui/components/*"],
      "@lib/*": ["src/bui/lib/*"],
    },
}

tips

重启VScode生效

  1. 在TS里引入
import Btn from '@componnets/Button/index';
import BasePage from '@lib/Page';


export default class Home extends BasePage {
    
}

如果这样就结束了,那我们还讲这个干吗?

在TS里这样写确实OK,也不会报错,那么我们实际运行,会报找不到模块错误。

我们看看编译后的JS代码


// import BasePage from '@lib/Page';

var Page_1 = require("@lib/Page");

@lib/Page 没有被替换成真实的路径。所以会报找不到模块

如何解决JS文件,路径alias没有被替换

  • 通过module-alias
// 安装 module-alias 包后,在package.json里写如下配置

"_moduleAliases": {
    "@components" : "./dist/bui/components",
    "@lib" : "./dist/bui/lib",
    "Component" : "./dist/bui/lib/component/index",
    "Page" : "./dist/bui/lib/page/index"
}

app.js引入包

// app.js
require('module-alias/register')

tips

这里的配置和我们在tsconfig.json一一对应的,但目的文件不是./src而是./dist

但是这个再小程序开发不支持npm的时候会报错,在支持npm的时候没问题

Uncaught Error: module "module-alias/register.js" is not defined
    at require (VM32 WAService.js:14)
    at VM32 WAService.js:14
    at app.js:1
    at require (VM32 WAService.js:14)
    at <anonymous>:1:1
    at HTMLScriptElement.scriptLoaded (appservice?t=1568950500318:3430)
    at HTMLScriptElement.script.onload (appservice?t=1568950500318:3442)
  • 通过构建工具

这里是自己通过编译后的js,正则匹配到我们目的字符串,然后替换成真实的相对路径

  • 通过tsconfig-paths

这个插件既支持node cli 又支持 webpack plugin,但不支持gulp, 可以点击详情了解用法

  • 通过gulp-ts-path-alias

yarn add gulp-ts-path-alias -D

// gulpfile.js
+  const tsProject = gulpTypescript.createProject('./tsconfig.json');

...
     .pipe(gulpSourceMaps.init())
-    .pipe(gulpTypescript.createProject('./tsconfig.json')())
+    .pipe(tsProject())
     .pipe(gulpSourceMaps.write())
+    .pipe(alias('.', tsProject.config.compilerOptions.paths))
     .pipe(dest(DIST_DIR));

这样可以正常使用了。

tips

不支持如下配置,具体到文件的配置

"Component" : "./dist/bui/lib/component/index",
"Page" : "./dist/bui/lib/page/index"