Title: Path mappings based module resolution · Issue #5039 · microsoft/TypeScript · GitHub
Open Graph Title: Path mappings based module resolution · Issue #5039 · microsoft/TypeScript
X Title: Path mappings based module resolution · Issue #5039 · microsoft/TypeScript
Description: Proposed module resolution strategy UPDATE: proposal below is updated based on the results of the design meeting. Initial version can be found here. Primary differences: instead of having baseUrl as a separate module resolution strategy ...
Open Graph Description: Proposed module resolution strategy UPDATE: proposal below is updated based on the results of the design meeting. Initial version can be found here. Primary differences: instead of having baseUrl a...
X Description: Proposed module resolution strategy UPDATE: proposal below is updated based on the results of the design meeting. Initial version can be found here. Primary differences: instead of having baseUrl a...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/5039
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Path mappings based module resolution","articleBody":"# Proposed module resolution strategy\n\n**UPDATE**: proposal below is updated based on the results of the design meeting. \nInitial version can be found [here](https://gist.github.com/vladima/725949fd9464e6a94771). \n\nPrimary differences:\n- instead of having `baseUrl` as a separate module resolution strategy we are introducing a set of properties\n that will allow to customize resoluton process in existing resolution strategies but base strategy still is used as a fallback.\n- `rootDirs` are decoupled from the `baseUrl` and can be used without it.\n\nCurrently TypeScript supports two ways of resolving module names: `classic` (module name always resolves to a file, module are searched using a folder walk)\nand `node` (uses [rules](https://github.com/Microsoft/TypeScript/issues/2338) similar to [node module loader](https://nodejs.org/api/modules.html#modules_all_together), was introduced in TypeScript 1.6). \nThese approaches worked reasonably well but they were not able to model _baseUrl_ based mechanics used by\n[RequireJS](http://requirejs.org/docs/api.html#config-baseUrl) or [SystemJS](https://github.com/systemjs/systemjs/blob/master/docs/overview.md#baseurl). \n\nWe could introduce third type of module resolution that will fill this gap but this will mean that once user has started to use this new type then support to \ndiscover typings embedded in node modules (and distributed via `npm`) is lost. Effectively user that wanted both to use `baseUrl` to refer to modules defined inside the project\nand rely on `npm` to obtain modules with typings will have to choose what part of the system will be broken.\n\nInstead of doing this we'll allow to declare a set of properties that will augment existing module resolution strategies. These properties are:\n`baseUrl`, `paths` and `rootDirs` (`paths` can only be used if `baseUrl` is set). If at least one of these properties is defined then compiler will try to \nuse it to resolve module name and if it fail - will fallback to a default behavior for a current resolution strategy.\n\nAlso choice of resolution strategy determines what does it mean to load a module from a given path. To be more concrete given some module name `/a/b/c`:\n- `classic` resolver will check for the presense of files `/a/b/c.ts`, `/a/b/c.tsx` and `/a/b/c.d.ts`.\n- `node` resolver will first try to load module as file by probing the same files as `classic` and then try to load module from directory \n (check `/a/b/c/index` with supported extension, then peek into `package.json` etc. More details can be found in [this issue](https://github.com/Microsoft/TypeScript/issues/2338)) \n# Properties\n- [baseUrl](#baseUrl)\n- [path mappings](#pathMappings)\n- [rootDirs](#rootDirs)\n## BaseUrl \u003ca id=\"baseUrl\">\u003c/a>\n\nAll non-rooted paths are computed relative to _baseUrl_. \nValue of _baseUrl_ is determined as either:\n- value of _baseUrl_ command line argument (if given path is relative it is computed based on current directory)\n- value of _baseUrl_ propery in 'tsconfig.json' (if given path is relative it is computed based on then location of 'tsconfig.json')\n## Path mappings \u003ca id=\"pathMappings\">\u003c/a>\n\nSometimes modules are not directly located under _baseUrl_. It is possible to control how locations are computed in such cases\nusing path mappings. Path mappings are specified using the following JSON structure:\n\n``` javascript\n{\n \"paths\": {\n \"pattern-1\": [\"list of substitutions\"],\n \"pattern-2\": [\"list of substitutions\"],\n ...\n \"pattern-N\": [\"list of substitutions\"]\n }\n}\n```\n\nPatterns and substitutions are strings that can have zero or one asteriks ('*'). \nInterpretation of both patterns and substitutions will be described in [Resolution process](#resolutionProcess) section.\n## Resolution process \u003ca id=\"resolutionProcess\">\u003c/a>\n\nNon-relative module names are resolved slightly differently comparing \nto relative (start with \"./\" or \"../\") and rooted module names (start with \"/\", drive name or schema). \n### Resolution of non-relative module names (mostly matches SystemJS)\n\n``` javascript\n\n// mimics path mappings in SystemJS\n// NOTE: moduleExists checks if file with any supported extension exists on disk\nfunction resolveNonRelativeModuleName(moduleName: string): string {\n // check if module name should be used as-is or it should be mapped to different value\n let longestMatchedPrefixLength = 0;\n let matchedPattern: string;\n let matchedWildcard: string;\n\n for (let pattern in config.paths) {\n assert(pattern.countOf('*') \u003c= 1);\n let indexOfWildcard = pattern.indexOf('*'); \n if (indexOfWildcard !== -1) {\n // if pattern contains asterisk then asterisk acts as a capture group with a greedy matching\n // i.e. for the string 'abbb' pattern 'a*b' will get 'bb' as '*'\n\n // check if module name starts with prefix, ends with suffix and these two don't overlap\n let prefix = pattern.substr(0, indexOfWildcard);\n let suffix = pattern.substr(indexOfWildcard + 1);\n if (moduleName.length >= prefix.length + suffix.length && \n moduleName.startsWith(prefix) &&\n moduleName.endsWith(suffix)) {\n\n // use length of matched prefix as betterness criteria\n if (longestMatchedPrefixLength \u003c prefix.length) {\n // save length of the prefix\n longestMatchedPrefixLength = prefix.length;\n // save matched pattern\n matchedPattern = pattern;\n // save matched wildcard content \n matchedWildcard = moduleName.substr(prefix.length, moduleName.length - suffix.length);\n }\n }\n }\n else {\n // pattern does not contain asterisk - module name should exactly match pattern to succeed\n if (pattern === moduleName) {\n // save pattern\n matchedPattern = pattern;\n // drop saved wildcard match \n matchedWildcard = undefined;\n // exact match is found - can exit early \n break;\n }\n }\n }\n\n if (!matchedPattern) {\n // no pattern was matched so module name can be used as-is\n let path = combine(baseUrl, moduleName);\n return moduleExists(path) ? path : undefined;\n }\n\n // some pattern was matched - module name needs to be substituted\n let substitutions = config.paths[matchedPattern].asArray();\n for (let subst of substitutions) {\n assert(substs.countOf('*') \u003c= 1);\n // replace * in substitution with matched wildcard\n let path = matchedWildcard ? subst.replace(\"*\", matchedWildcard) : subst;\n // if substituion is a relative path - combine it with baseUrl\n path = isRelative(path) ? combine(baseUrl, path) : path;\n if (moduleExists(path)) {\n return path;\n }\n }\n\n return undefined; \n}\n\n```\n### Resolution of relative module names\n#### Default resolution logic (matches SystemJS)\n\nRelative module names are computed treating location of source file that contains the import as base folder.\nPath mappings are not applied.\n\n``` javascript\nfunction resolveRelativeModuleName(moduleName: string, containingFile: string): string {\n let path = combine(getDirectoryName(containingFile), moduleName);\n return moduleExists(path) ? path : undefined;\n}\n```\n#### Using `rootDirs`\u003ca id=\"rootDirs\">\u003c/a>\n\n'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if multiple project roots were merged together in one folder. For example project contains source files that are located in different directories on then file system (not under the same root) but user still still prefers to use relative module names because in runtime such names can be successfully resolved due to bundling.\n\nFor example consider this project structure:\n\n```\n shared\n └── projects\n └── project\n └── src\n ├── viewManager.ts (imports './views/view1')\n └── views\n └── view2.ts (imports './view1')\n userFiles\n └── project\n └── src\n └── views\n └── view1.ts (imports './view2')\n```\n\nLogically files in `userFiles/project` and `shared/projects/project` belong to the same project and\nafter build they indeed will be bundled together.\n\nIn order to support this we'll add configuration property \"rootDirs\":\n\n``` json\n{\n \"rootDirs\": [\n \"rootDir-1/\",\n \"rootDir-2/\",\n ...\n \"rootDir-n/\"\n ]\n}\n```\n\nThis property stores list of base folders, every folder name can be either absolute or relative. \nElements in `rootDirs` that represent non-absolute paths will be converted to absolute using location of tsconfig.json as a base folder - this is the common approach for all paths defined in tsconfig.json\n\n``` javascript\n///Algorithm for resolving relative module name\nfunction resolveRelativeModuleName(moduleName: string, containingFile: string): string {\n // convert relative module name to absolute using location of containing file\n // this step is exactly the same as when doing resolution without path mapping\n let path = combine(getDirectoryName(containingFile), moduleName);\n\n // convert absolute module name to non-relative\n // try to find element in 'rootDirs' that is the longest prefix for \"path' and return path.substr(prefix.length) as non-relative name\n let { matchingRootDir, nonRelativeName } = tryFindLongestPrefixAndReturnSuffix(rootDirs, path);\n if (!matchingRootDir) {\n // cannot extract non relative name\n return undefined;\n }\n // first try to load module from initial location\n if (moduleExists(path)) {\n return path;\n }\n // then try other entries in rootDirs\n for (const rootDir of rootDirs) {\n if (rootDir === matchingRootDir) {\n continue;\n }\n const candidate = combine(rootDir, nonRelativeName);\n if (moduleExists(candidate)) {\n return candidate;\n }\n }\n // failure case\n return undefined;\n}\n```\n\nConfiguration for the example above:\n\n``` json\n{\n \"rootDirs\": [\n \"userFiles/project/\",\n \"/shared/projects/project/\"\n ]\n}\n```\n### Example 1\n\n```\nprojectRoot\n├── folder1\n│ └── file1.ts (imports 'folder2/file2')\n├── folder2\n│ ├── file2.ts (imports './file3')\n│ └── file3.ts\n└── tsconfig.json\n\n```\n\n``` javascript\n// configuration in tsconfig.json\n{\n \"baseUrl\": \".\"\n}\n```\n- import 'folder2/file2'\n 1. _baseUrl_ is specified in configuration and has value '.' -> _baseUrl_ is computed relative to \n the location of tsconfig.json -> `projectRoot`\n 2. path mappings are not available -> path = moduleName\n 3. resolved module file name = combine(baseUrl, path) -> `projectRoot/folder2/file2.ts`\n- import './file3'\n 1. moduleName is relative and _rootDirs_ are not specified in configuration - compute module name\n relative to the location of containing file: resolved module file name = `projectRoot/folder2/file3.ts`\n### Example 2\n\n```\nprojectRoot\n├── folder1\n│ ├── file1.ts (imports 'folder1/file2' and 'folder2/file3')\n│ └── file2.ts\n├── generated\n│ ├── folder1\n│ └── folder2\n│ └── file3.ts\n└── tsconfig.json\n\n```\n\n``` javascript\n// configuration in tsconfig.json\n{\n \"baseUrl\": \".\",\n \"paths\": {\n \"*\": [\n \"*\",\n \"generated/*\" \n ]\n }\n}\n```\n- import 'folder1/file2'\n 1. _baseUrl_ is specified in configuration and has value '.' -> _baseUrl_ is computed relative to \n the location of tsconfig.json -> `projectRoot`\n 2. configuration contains path mappings.\n 3. pattern '*' is matched and wildcard captures the whole module name\n 4. try first substitution in the list: '*' -> `folder1/file2`\n 5. result of substitution is relative name - combine it with _baseUrl_ -> `projectRoot/folder1/file2.ts`.\n This file exists.\n- import 'folder2/file2'\n 1. _baseUrl_ is specified in configuration and has value '.' -> _baseUrl_ is computed relative to \n the location of tsconfig.json and will be folder that contains tsconfig.json\n 2. configuration contains path mappings.\n 3. pattern '*' is matched and wildcard captures the whole module name\n 4. try first substitution in the list: '*' -> `folder2/file3`\n 5. result of substitution is relative name - combine it with _baseUrl_ -> `projectRoot/folder2/file3.ts`.\n File does not exists, move to the second substitution\n 6. second substitution 'generated/*' -> `generated/folder2/file3` \n 7. result of substitution is relative name - combine it with _baseUrl_ -> `projectRoot/generated/folder2/file3.ts`.\n File exists\n## Example 3\n\n```\nrootDir\n├── folder1\n│ └── file1.ts (imports './file2')\n├── generated\n│ ├── folder1\n│ │ ├── file2.ts\n│ │ └── file3.ts (imports '../folder1/file1')\n│ └── folder2\n└── tsconfig.json\n```\n\n``` javascript\n// configuration in tsconfig.json\n{\n \"rootDirs\": [\n \"./\",\n \"./generated/\" \n ],\n}\n```\n\nAll non-rooted entries in `rootDirs` are expanded using location of tsconfig.json as base location so after expansion `rootDirs` will\nlook like this:\n\n``` json\n \"rootDirs\": [\n \"rootDir/\",\n \"rootDir/generated/\" \n ],\n```\n- import './file2'\n 1. name is relative, first make it absolute using location of containing file as base location - `rootDir/folder1/file2`\n 2. for this string find the longest prefix in `rootDirs` - `rootDir/` and for this prefix compute as suffix - `folder1/file2`\n 3. since matching entry in `rootDirs` was found try to resolve module using `rootDir` - first check if `rootDir/folder1/file2` \n can be resolved as module - such module does not exist\n 4. try remaining entries in `rootDirs` - check if module `rootDir/generated/folder1/file2` exists - yes.\n- import '../folder1/file1'\n 1. name is relative, first make it absolute using location of containing file as base location - `rootDir/generated/folder1/file1`\n 2. for this string find the longest prefix in `rootDirs` - `rootDir/generated` and for this prefix compute as suffix - `folder1/file1`\n 3. since matching entry in `rootDirs` was found try to resolve module using `rootDir` - first check if `rootDir/generated/folder1/file1` \n can be resolved as module - such module does not exist\n 4. try remaining entries in `rootDirs` - check if module `rootDir/folder1/file1` exists - yes.\n","author":{"url":"https://github.com/vladima","@type":"Person","name":"vladima"},"datePublished":"2015-09-30T17:42:16Z","url":"https://github.com/microsoft/TypeScript/issues/5039"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:426044ba-089c-18fd-8084-f6d301a5c19c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9C1E:4CE06:1A0EED:226F15:6AFBB26C |
| html-safe-nonce | f56cb026ff6f6b9b70846ebf0572a6600c2e484b7a30905625fc92cbb05c7829 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5QzFFOjRDRTA2OjFBMEVFRDoyMjZGMTU6NkFGQkIyNkMiLCJ2aXNpdG9yX2lkIjoiODMxMjE2NzM0MjA5MTc3NjYyMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 0310bbb2ac1a04283c80ac591292a4fee32f18146e0de1e10bf88874e45a3d77 |
| hovercard-subject-tag | issue:109143324 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/5039/issue_layout |
| twitter:image | https://opengraph.githubassets.com/f5a2eb52792f6b29bce932624d1da75faff408b334e3cd1219790b95fb11d28a/microsoft/TypeScript/issues/5039 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/f5a2eb52792f6b29bce932624d1da75faff408b334e3cd1219790b95fb11d28a/microsoft/TypeScript/issues/5039 |
| og:image:alt | Proposed module resolution strategy UPDATE: proposal below is updated based on the results of the design meeting. Initial version can be found here. Primary differences: instead of having baseUrl a... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | vladima |
| hostname | github.com |
| expected-hostname | github.com |
| None | 2b2ef9c1578c18d8ed27027940544c958743213cf4461659f14d3ccdf51e162c |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | e4cce0e99cf61481a318ff12c2e8580153a6c7c6 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width