如何在 tsconfig.json 中使用路径? [英] How to use paths in tsconfig.json?

查看:63
本文介绍了如何在 tsconfig.json 中使用路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关

项目组织有点奇怪,因为我们有一个包含项目和库的单一存储库.项目按公司和浏览器/服务器/通用分组.

如何在 tsconfig.json 中配置路径,而不是:

import {Something } from "../../../../../lib/src/[browser/server/universal]/...";

我可以使用:

import {Something } from "lib/src/[browser/server/universal]/...";

webpack 配置中是否还需要其他内容?还是 tsconfig.json 就够了?

解决方案

这可以在您的 tsconfig.json 文件中设置,因为它是 TS 功能.

你可以这样做:

编译器选项":{baseUrl": src",//如果paths"不存在,则必须指定此项是....路径":{"@app/*": ["app/*"],"@config/*": ["app/_config/*"],"@environment/*": ["environments/*"],"@shared/*": ["app/_shared/*"],@helpers/*":[helpers/*"]},...

请记住,您要引用的路径以您的 baseUrl 作为您指向的路线的基础,并且如文档中所述,这是强制性的.

字符@"不是必需的.

按照这种方式进行设置后,您可以像这样轻松地使用它:

import { Yo } from '@config/index';

您可能会注意到的唯一一件事是智能感知在当前的最新版本中不起作用,因此我建议遵循索引约定来导入/导出文件.

<块引用>

https://www.typescriptlang.org/docs/手册/模块分辨率.html#path-mapping

I was reading about path-mapping in tsconfig.json and I wanted to use it to avoid using the following ugly paths:

The project organization is a bit weird because we have a mono-repository that contains projects and libraries. The projects are grouped by company and by browser / server / universal.

How can I configure the paths in tsconfig.json so instead of:

import { Something } from "../../../../../lib/src/[browser/server/universal]/...";

I can use:

import { Something } from "lib/src/[browser/server/universal]/...";

Will something else be required in the webpack config? or is the tsconfig.json enough?

解决方案

This can be set up on your tsconfig.json file, as it is a TS feature.

You can do like this:

"compilerOptions": {
        "baseUrl": "src", // This must be specified if "paths" is.
         ...
        "paths": {
            "@app/*": ["app/*"],
            "@config/*": ["app/_config/*"],
            "@environment/*": ["environments/*"],
            "@shared/*": ["app/_shared/*"],
            "@helpers/*": ["helpers/*"]
        },
        ...

Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the doc.

The character '@' is not mandatory.

After you set it up on that way, you can easily use it like this:

import { Yo } from '@config/index';

the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

这篇关于如何在 tsconfig.json 中使用路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆