1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { readFileSync } from "fs"; 17import * as ts from "typescript"; 18 19export function creatAstFromSnippet(snippet: string): ts.SourceFile { 20 let sourceFile = ts.createSourceFile("snippet.ts", snippet, ts.ScriptTarget.ES2015, true); 21 return sourceFile; 22} 23 24/** It would be tricky here to use relative path, so please use an absolute path instead. 25 * For how to use this function, please refer to example_asthelper.ts 26 */ 27export function creatAstFromFile(fileName: string): ts.SourceFile { 28 let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, true); 29 return sourceFile; 30} 31 32module.exports = { 33 creatAstFromSnippet: creatAstFromSnippet, 34 creatAstFromFile: creatAstFromFile 35} 36