tsconfig.json İçinde “paths” Anahtarı

Cem Topkaya
7 min readMay 6, 2019

--

  • Typescript ayar dosyası oluşturmak
  • node_modules
  • paths
  • Imported module is being loaded from a relative path. Please use an absolute path

Önce basit bir typescript projesi oluşturalım. Typescript dosyalarının .js dosyalarına transpile edileceğini biliyoruz. Peki bu .js dosyalarını nasıl çalıştıracağız. Eğer bir web broswer(chrome, ie, firefox vs) üstünde bu javascript dosyalarını çalıştırmayacaksak geriye nodejs motoru kalıyor. O halde önce npm init -y ile bulunduğumuz boş klasörde package.json dosyası oluşturalım ve npm install typescript --save-dev komutuyla sadece geliştirme aşamasında yazdığımız .ts dosyalarını .js dosyalarına dönüştürecek(transpile) edecek typescript derleyicisini --save-dev anahtarıyla “geliştirme süresinde bağımlılığımız olan paketler” listesine yani “devDependencies” anahtarında tutalım.

Veya tüm uygulamalarınız tarafından erişilebilsin ve bir daha typescript derleyici indirmemek için npm install typescript -g komutuyla indirebiliriz.

npm init -y && tsc --init

Typescript ayar dosyası oluşturmak

tsc --init

Bu komut bize tsconfig.json dosyasını oluşturacaktır.

{"compilerOptions": {/* Basic Options */
"target": "es5",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [],
/* Specify library files to be included in the compilation. */
// "allowJs": true,
/* Allow javascript files to be compiled. */
// "checkJs": true,
/* Report errors in .js files. */
// "jsx": "preserve",
/* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true,
/* Generates corresponding '.d.ts' file. */
// "declarationMap": true,
/* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true,
/* Generates corresponding '.map' file. */
// "outFile": "./",
/* Concatenate and emit output to single file. */
// "outDir": "./",
/* Redirect output structure to the directory. */
// "rootDir": "./",
/* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true,
/* Enable project compilation */
// "incremental": true,
/* Enable incremental compilation */
// "tsBuildInfoFile": "./",
/* Specify file to store incremental compilation information */
// "removeComments": true,
/* Do not emit comments to output. */
// "noEmit": true,
/* Do not emit outputs. */
// "importHelpers": true,
/* Import emit helpers from 'tslib'. */
// "downlevelIteration": true,
/* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true,
/* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true,
/* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true,
/* Enable strict null checks. */
// "strictFunctionTypes": true,
/* Enable strict checking of function types. */
// "strictBindCallApply": true,
/* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true,
/* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true,
/* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true,
/* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true,
/* Report errors on unused locals. */
// "noUnusedParameters": true,
/* Report errors on unused parameters. */
// "noImplicitReturns": true,
/* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true,
/* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node",
/* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./",
/* Base directory to resolve non-absolute module names. */
// "paths": {},
/* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [],
/* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [],
/* List of folders to include type definitions from. */
// "types": [],
/* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true,
/* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */// "preserveSymlinks": true,
/* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "",
/* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "",
/* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true,
/* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true,
/* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true,
/* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true,
/* Enables experimental support for emitting type metadata for decorators. */

node_modules

içindeki paketlerde “package.json” dikkate alınır. main anahtarındaki dosyadan dışarıya ihraç edilen tipler kullanılır.

import { yazdir } from "hede"

Satırıyla paket kullanılmak isteniyorsa, projenin node_modules klasöründe “hede” isimli paket aranır, node_modules içindeki entrypoint dosyasını işaret eden “main” anahtarında verilen dosyayı okur. Bu dosyada export edilen “yazdir” tipini böylece içeri alır (import). node_modules Klasöründen bir paket gibi okursa package.json’ı dikkate alır. Eğer node_modules içinde istenilen paket bulunamazsa tsconfig.json içindeki paths anahtarına bakılır.

paths

içindeki takma adlarla verilen modülleri değerleri olan klasörlerde arayacaklar. tsconfig.json içinde paths anahtarı şöyle verilmiş olursa:

paths:{
"takma_modul_adi" : [ "hodo/hede" ]
}

takma_modul_adi” isimli modül için tsconfig.json ile aynı dizinde (baseUrl = ./ olduğu için) “paths” anahtarının içine bakacak ve bulduğunda “hodo/hede” klasörünün index.js dosyasında export edilen tipleri import edebilecek.

Unutmayın eğer node_modules içinde bulamadıysa “hede” paketini, bu kez tsconfig.json içinde verilmiş “paths” içinde “hede” yi arar. node_modules içinde bulursa onun içindeki entry point dosyasındaki tipleri arar. paths anahtarındaki klasöre gittiyse package.json içindeki “main” anahtarının gösterdiği dosyayı !DEĞİL! index.js içinde export edilen tipleri arar.

Bir de Şöyle Anlatalım

projects dizininde iki proje var:

- kutuphane (içinde component, module ve service var)

- uygulama (kutuphanede yarattığımız bileşenleri burada test uygulaması içinde kullanacak olalım)

Uygulama projesinde import ile dependencies içindeki paketlerden “şeyler” çekiyoruz. Ancak kutuphane projesini npm install ile yüklemediğimiz için uygulama projesinden erişemeyiz.

Typescript kodu yazdığımızı hatırlayalım bir kez daha. Uygulama projesinde herhangi bir *.ts dosyasında import yaptığımızda

import { } from 'kutuphane';

indirilmiş paketlerde ‘kutuphane’ isimli paketi bulamazsa baksın diye paths anahtarına yandaki gibi hangi dizine bakması gerektiğini yazıyoruz.

Ref: https://www.typescriptlang.org

tslint İle Bezeyelim

Imported module is being loaded from a relative path. Please use an absolute path

tslint Sayesinde kodumuzu daha derli toplu yaptırmak için bizi zorlayan bir danışmanımız oluyor. Uyarılarını dikkate alalım!

Aşağıdaki uyarıda “İçe aktarılan modül göreceli bir yoldan yükleniyor.” diyor ve ekliyor “Lütfen mutlak bir yol kullanın”.

Imported module is being loaded from a relative path. Please use an absolute path: import { module2, SayCommand, module1 } from '../lib/commands/say'; (no-relative-imports)tslint(1)

Göreceli yoldan kastı “../” veya “./” diye bulunduğumuz dizine görece başka bir dizini işaret ediyor olmamız.

Seçeneklerimiz:

  • Bu kuralı o satır için “devre dışı bırakacağız” (disable)
  • Önümüze gelen her görece içeri alma satırında bunu yazmamak için tslint.json dosyasında bu kuralı devre dışı bırakacağız
  • Daha temiz yaklaşım ile yukarıdaki seçimler yerine tsconfig.json içinde baseUrl özelliğine kök dizini işaret edip ilgili dosyayı kök dizinden sonraki klasörleri göstererek (mutlak dizin yapısında) vereceğiz.
Artık daha farklı bir uyarı veriyor ama daha iyi bir yol daha var
  • İçeri alacağımız dosyanın olduğu dizini bir paket gibi gösterebiliriz. Bunun için paths özelliğine aşağıdaki gibi ayar yapabiliriz. Paths içindeki paket tanımınız eğer aşağıdaki örnek gibi tanımlanıyorsa yani bir dizini işaret ediyorsa paket adına @ karakteri koymak gerçek bir paket adıyla karışmasının önüne geçmenizi sağlar. Yani “@command/say” diyerek bir “command” adında bir node_modules içinde yer alan paket adıyla karışmasını önlemiş oluruz.

--

--

Cem Topkaya
Cem Topkaya

Written by Cem Topkaya

Evlat, kardeş, ağabey, eş, baba, müzik sever, öğrenmek ister, paylaşmaya can atar, iyi biri olmaya çalışır, hakkı geçenlerden helallik ister vs.

No responses yet