development

tsconfig.json에서 경로를 사용하는 방법은 무엇입니까?

big-blog 2020. 7. 22. 07:34
반응형

tsconfig.json에서 경로를 사용하는 방법은 무엇입니까?


나는 경로 매핑대해 읽고 있었고 tsconfig.json다음과 같은 추한 경로를 사용하지 않기 위해 그것을 사용하고 싶었습니다.

여기에 이미지 설명을 입력하십시오

프로젝트 조직은 프로젝트와 라이브러리를 포함하는 단일 저장소를 가지고 있기 때문에 약간 이상합니다. 프로젝트는 회사 및 브라우저 / 서버 / 유니버설별로 그룹화됩니다.

여기에 이미지 설명을 입력하십시오

다음 tsconfig.json대신 경로를 구성하는 방법은 무엇입니까?

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

나는 사용할 수 있습니다 :

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

웹팩 구성에 다른 것이 필요합니까? 아니면 tsconfig.json충분합니까?


tsconfig.json 파일은 TS 기능이므로 설정할 수 있습니다.

당신은 이렇게 할 수 있습니다 :

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

참조하려는 경로는 baseUrl을 가리키는 경로의 기준으로 사용하며 문서에 설명 된대로 필수입니다.

문자 '@'은 필수가 아닙니다.

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

UPDATE Check out this example I made to showcase how is mapping into a single file:

https://github.com/ialex90/TypeScript-Node-Starter/commit/a4e8cc1f8f8d5176e0099e05b51f97b0ef4bebea


You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

// tsconfig.json
{
  "compilerOptions": {
    ...
    "rootDir": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

For webpack you might also need to add module resolution. For webpack2 this could look like

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

Check this similar solutions with asterisk

  "baseUrl": ".",
  "paths": {
    "*": [
      "node_modules/*",
      "src/types/*"
    ]
  },

Alejandros answer worked for me, but as I'm using the awesome-typescript-loader with webpack 4, I also had to add the tsconfig-paths-webpack-plugin to my webpack.config file for it to resolve correctly


If you are using paths, you will need to change back absolute paths to relative paths for it to work after compiling typescript into plain javascript using tsc.

Most popular solution for this has been tsconfig-paths so far.

I've tried it, but it did not work for me for my complicated setup. Also, it resolves paths in run-time, meaning overhead in terms of your package size and resolve performance.

So, I wrote a solution myself, tscpaths.

I'd say it's better overall because it replaces paths at compile-time. It means there is no runtime dependency or any performance overhead. It's pretty simple to use. You just need to add a line to your build scripts in package.json.

The project is pretty young, so there could be some issues if your setup is very complicated. It works flawlessly for my setup, though my setup is fairly complex.


if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):

// tsconfig.json
{
  "compilerOptions": {
    ...
    "rootDir": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}    

// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

resolve: {
    plugins: [
        new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
    ]
}

Advanced path resolution in TypeScript 2.0


This works for me:

 yarn add --dev tsconfig-paths

 ts-node -r tsconfig-paths/register <your-index-file>.ts

This loads all paths in tsconfig.json. A sample tsconfig.json:

{
    "compilerOptions": {
        {…}
        "baseUrl": "./src",
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

Make sure you have both baseUrl and paths for this to work

And then you can import like :

import {AlarmIcon} from 'assets/icons'

/ starts from the root only, to get the relative path we should use ./ or ../


Its kind of relative path Instead of the below code

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

We can avoid the "../../../../../" its looking odd and not readable too.

So Typescript config file have answer for the same. Just specify the baseUrl, config will take care of your relative path.

way to config: tsconfig.json file add the below properties.

"baseUrl": "src",
    "paths": {
      "@app/*": [ "app/*" ],
      "@env/*": [ "environments/*" ]
    }

So Finally it will look like below

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

Its looks simple,awesome and more readable..


It looks like there has been an update to React that doesn't allow you to set the "paths" in the tsconfig.json anylonger.

Nicely React just outputs a warning:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

then updates your tsconfig.json and removes the entire "paths" section for you. There is a way to get around this run

npm run eject

그러면 프로젝트에 디렉토리 및 빌드 / 구성 파일을 create-react-scripts추가하여 모든 설정을 추출합니다 . 또한 파일 을 업데이트하여 모든 것이 어떻게 작성되고 이름이 지정되는지 등을 훨씬 더 제어 할 수 있습니다.configscripts{project}/config/*

그런 다음 업데이트 tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./src",
        {…}
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

참고 URL : https://stackoverflow.com/questions/43281741/how-to-use-paths-in-tsconfig-json

반응형