解析 typescript 文件以获取导出的 const 变量

Ira*_*ris 3 javascript regex parsing typescript angular

有没有办法从 .js 文件解析environment.ts 文件?

export const environment = {
    ...,
    production: false,
    ...
}; 
Run Code Online (Sandbox Code Playgroud)

就像是

beforePrepare.js

module.exports = function (ctx) {
    let environmet = TOOL.parse(src/environments/environment.ts);
    console.log(environment); --> PRINT {..., production: false, ...}
}
Run Code Online (Sandbox Code Playgroud)

正则表达式也能完成这项工作吗?

我需要这个来实现科尔多瓦钩子

kol*_*kol 5

正则表达式可以用作快速但肮脏的解决方案:

const s = `
// Some comment
export const environment = {
  production: false,
  apiUrl: 'http://my-api-url',
  testUser: {
    name: 'John Doe',
    age: 25
  }
};
export const otherStuff = {
  answer: 42
};
`;

const regex = /export const environment = (\{[^;]*\});/m;
const match = regex.exec(s);
const environment = eval(`(${match[1]})`);
console.log(environment);
Run Code Online (Sandbox Code Playgroud)

对于更复杂的情况,您需要 TypeScript 解析器。