Created
March 16, 2020 20:30
-
-
Save lac5/35ba43b6095a27ec67eb6fb279ad65f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This script reads the nearby global.d.ts file and exports a list of imports as | |
an object. Imports need to follow the same structure as the example below. This | |
script only works with default exports but could be modified to use named | |
exports instead. | |
Example: | |
`global.d.ts` | |
import _$ from 'jquery'; | |
import _Handlebars from 'handlebars'; | |
import whatever from './foobar.js'; | |
declare global { | |
interface Window { | |
$: typeof _$; | |
Handlebars: typeof _Handlebars; | |
foobar: typeof whatever; | |
} | |
} | |
`[any].js` | |
const globals = require('./global.js'); | |
console.dir(globals); | |
// { | |
// '$': 'jquery', | |
// Handlebars: 'handlebars', | |
// foobar: './foobar.js' | |
// } | |
*/ | |
const fs = require('fs'); | |
const { parse } = require('@typescript-eslint/typescript-estree'); | |
function getGlobals(input) { | |
const ast = parse(input); | |
const imports = {}; | |
const globals = {}; | |
for (let statement of ast.body) { | |
if (statement.type === 'ImportDeclaration') { | |
for (let specifier of statement.specifiers) { | |
if (specifier.type === 'ImportDefaultSpecifier') { | |
imports[specifier.local.name] = statement.source.value; | |
} | |
} | |
} else if (statement.type === 'TSModuleDeclaration') { | |
if ( statement.id.name !== 'global' | |
|| statement.body.type !== 'TSModuleBlock' | |
) continue; | |
for (let globalVar of statement.body.body) { | |
if ( globalVar.type !== 'TSInterfaceDeclaration' | |
|| globalVar.id.name !== 'Window' | |
) continue; | |
for (let windowVar of globalVar.body.body) { | |
if ( windowVar.type !== 'TSPropertySignature' | |
|| windowVar.typeAnnotation.type !== 'TSTypeAnnotation' | |
|| windowVar.typeAnnotation.typeAnnotation.type !== 'TSTypeQuery' | |
|| windowVar.typeAnnotation.typeAnnotation.exprName.type !== 'Identifier' | |
) continue; | |
if (imports[windowVar.typeAnnotation.typeAnnotation.exprName.name]) { | |
globals[windowVar.key.name] = imports[windowVar.typeAnnotation.typeAnnotation.exprName.name]; | |
} | |
} | |
} | |
} | |
} | |
return globals; | |
} | |
/** @type {{ [name: string]: string }} */ | |
module.exports = getGlobals(fs.readFileSync(__dirname + '/global.d.ts')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment