Created
June 11, 2024 15:21
-
-
Save stepankuzmin/07908da45166a62cc46d00a027ae53c4 to your computer and use it in GitHub Desktop.
Migrate code to `gl-matrix` v4
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
import babel from '@babel/core'; | |
import traverse from '@babel/traverse'; | |
import generator from '@babel/generator'; | |
function capitalizeFirstLetter(string) { | |
return string.charAt(0).toUpperCase() + string.slice(1); | |
} | |
function migrate() { | |
const input = ` | |
import {mat2} from 'gl-matrix'; | |
import {mat3, mat4} from 'gl-matrix'; | |
import type {vec2} from 'gl-matrix'; | |
import type {vec3, vec4} from 'gl-matrix'; | |
`; | |
const ast = babel.parse(input, { | |
sourceType: 'module', | |
plugins: ['@babel/plugin-transform-typescript'] | |
}); | |
traverse.default(ast, { | |
ImportDeclaration(path) { | |
const source = path.node.source.value; | |
if (source === 'gl-matrix') { | |
if (path.node.specifiers.length === 1) { | |
const specifier = path.node.specifiers[0]; | |
path.node.source.value = `gl-matrix/dist/esm/f64/${specifier.local.name}.js`; | |
specifier.local.name = capitalizeFirstLetter(specifier.local.name); | |
specifier.imported.name = capitalizeFirstLetter(specifier.imported.name); | |
} else { | |
const imports = []; | |
for (const specifier of path.node.specifiers) { | |
const importDeclaration = babel.types.importDeclaration( | |
[specifier], | |
babel.types.stringLiteral(`gl-matrix/dist/esm/f64/${specifier.local.name}.js`) | |
); | |
// Use the same import kind as the original import | |
importDeclaration.importKind = path.node.importKind; | |
specifier.local.name = capitalizeFirstLetter(specifier.local.name); | |
specifier.imported.name = capitalizeFirstLetter(specifier.imported.name); | |
imports.push(importDeclaration); | |
} | |
path.replaceWithMultiple(imports); | |
} | |
} | |
} | |
}); | |
const {code: output} = generator.default(ast); | |
console.log('\n\n'); | |
console.log(input); | |
console.log('\n\n'); | |
console.log(output); | |
console.log('\n\n'); | |
} | |
migrate(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment