MCPcopy
hub / github.com/lingodotdev/lingo.dev / createImportDeclaration

Function createImportDeclaration

packages/compiler/src/utils/index.ts:145–187  ·  view source on GitHub ↗
(
  ast: t.Node,
  localName: string,
  exportedName: string,
  moduleName: string[],
)

Source from the content-addressed store, hash-verified

143}
144
145function createImportDeclaration(
146 ast: t.Node,
147 localName: string,
148 exportedName: string,
149 moduleName: string[],
150): void {
151 traverse(ast, {
152 Program(path: NodePath<t.Program>) {
153 // Create the import specifier
154 const importSpecifier = t.importSpecifier(
155 t.identifier(localName),
156 t.identifier(exportedName),
157 );
158
159 // Check if we already have a non-type import from this module
160 const existingImport = path
161 .get("body")
162 .find(
163 (nodePath: NodePath) =>
164 t.isImportDeclaration(nodePath.node) &&
165 moduleName.includes(nodePath.node.source.value) &&
166 nodePath.node.importKind !== "type",
167 );
168
169 if (existingImport && t.isImportDeclaration(existingImport.node)) {
170 // Add to existing import declaration
171 existingImport.node.specifiers.push(importSpecifier);
172 } else {
173 // Create a new import declaration
174 const importDeclaration = t.importDeclaration(
175 [importSpecifier],
176 t.stringLiteral(moduleName[0]),
177 );
178
179 // Add it at the top of the file, after any existing imports
180 const lastImportIndex = findLastImportIndex(path);
181 path.node.body.splice(lastImportIndex + 1, 0, importDeclaration);
182 }
183
184 path.stop();
185 },
186 });
187}
188
189function findLastImportIndex(programPath: NodePath<t.Program>): number {
190 const body = programPath.node.body;

Callers 1

getOrCreateImportFunction · 0.85

Calls 1

traverseFunction · 0.50

Tested by

no test coverage detected