-
-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathservice-host.js
More file actions
57 lines (53 loc) · 1.65 KB
/
Copy pathservice-host.js
File metadata and controls
57 lines (53 loc) · 1.65 KB
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
50
51
52
53
54
55
56
57
const { dirname } = require('path');
const ts = require('typescript');
const { findTsconfig } = require('./find-tsconfig');
const { getCompilerOptions } = require('./get-compiler-options');
/**
* Create the most basic TS language service host for the given file to make import sorting work.
*
* @param {string} path path to file
* @param {string} content file's content
*
* @returns {ts.LanguageServiceHost}
*/
function getTypeScriptLanguageServiceHost(path, content) {
const tsconfig = findTsconfig(path);
const compilerOptions = getCompilerOptions(tsconfig);
const snapshot = ts.ScriptSnapshot.fromString(content);
return {
directoryExists: ts.sys.directoryExists,
fileExists: ts.sys.fileExists,
getDefaultLibFileName: ts.getDefaultLibFileName,
getDirectories: ts.sys.getDirectories,
readDirectory: ts.sys.readDirectory,
readFile: ts.sys.readFile,
getCurrentDirectory: () => (tsconfig ? dirname(tsconfig) : ts.sys.getCurrentDirectory()),
getCompilationSettings: () => compilerOptions,
getNewLine: () => ts.sys.newLine,
getScriptFileNames: () => [path],
getScriptVersion: () => '0',
getScriptSnapshot: (filePath) => {
if (filePath === path) {
return snapshot;
}
},
getScriptKind: (fileName) => {
const ext = fileName.substring(fileName.lastIndexOf('.') + 1);
switch (ext) {
case 'ts':
return ts.ScriptKind.TS;
case 'tsx':
return ts.ScriptKind.TSX;
case 'js':
return ts.ScriptKind.JS;
case 'jsx':
return ts.ScriptKind.JSX;
case 'json':
return ts.ScriptKind.JSON;
default:
return ts.ScriptKind.Unknown;
}
},
};
}
module.exports = { getTypeScriptLanguageServiceHost };