forked from eslint-community/eslint-plugin-n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap-typescript-extension.js
49 lines (44 loc) · 1.35 KB
/
map-typescript-extension.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"use strict"
const path = require("path")
const isTypescript = require("../util/is-typescript")
const mapping = {
".ts": ".js",
".cts": ".cjs",
".mts": ".mjs",
}
const reverseMapping = {
".js": ".ts",
".cjs": ".cts",
".mjs": ".mts",
}
/**
* Maps the typescript file extension that should be added in an import statement,
* based on the given file extension of the referenced file OR fallsback to the original given extension.
*
* For example, in typescript, when referencing another typescript from a typescript file,
* a .js extension should be used instead of the original .ts extension of the referenced file.
*
* @param {RuleContext} context
* @param {string} filePath The filePath of the import
* @param {string} fallbackExtension The non-typescript fallback
* @param {boolean} reverse Execute a reverse path mapping
* @returns {string} The file extension to append to the import statement.
*/
module.exports = function mapTypescriptExtension(
context,
filePath,
fallbackExtension,
reverse = false
) {
const ext = path.extname(filePath)
if (reverse) {
if (isTypescript(context) && ext in reverseMapping) {
return reverseMapping[ext]
}
} else {
if (isTypescript(context) && ext in mapping) {
return mapping[ext]
}
}
return fallbackExtension
}