|
1 | 1 | const { getParser } = require('codemod-cli').jscodeshift; |
2 | | -const { addImportStatement, writeImportStatements } = require('../utils'); |
3 | | -// const { getOptions } = require('codemod-cli'); |
4 | 2 |
|
5 | 3 | module.exports = function transformer(file, api) { |
6 | 4 | const j = getParser(api); |
7 | | - |
8 | 5 | const root = j(file.source); |
9 | 6 |
|
10 | | - addImportStatement(['hbs']); |
11 | | - writeImportStatements(j, root); |
| 7 | + writeImportStatement(j, root); |
12 | 8 |
|
13 | 9 | return root.toSource({ quote: 'single' }); |
14 | 10 | }; |
| 11 | + |
| 12 | +function writeImportStatement(j, root) { |
| 13 | + let body = root.get().value.program.body; |
| 14 | + |
| 15 | + // finding all 'htmlbars-inline-precompile' import statements |
| 16 | + const inlinePrecompileImportStatement = root.find(j.ImportDeclaration, { |
| 17 | + source: { |
| 18 | + value: 'htmlbars-inline-precompile', |
| 19 | + }, |
| 20 | + }); |
| 21 | + |
| 22 | + // if any imports from 'htmlbars-inline-precompile' exists, remove it and replace with a new import |
| 23 | + if (inlinePrecompileImportStatement.length !== 0) { |
| 24 | + inlinePrecompileImportStatement.remove(); |
| 25 | + |
| 26 | + // setting up 'hbs' as an identifier for import statement |
| 27 | + const hbs = 'hbs'; |
| 28 | + const hbsAsIdentifier = j.identifier(hbs); |
| 29 | + const variableId = j.importSpecifier(hbsAsIdentifier); |
| 30 | + |
| 31 | + // finding all 'ember-cli-htmlbars' import statements |
| 32 | + const emberCliImportStatement = root.find(j.ImportDeclaration, { |
| 33 | + source: { |
| 34 | + value: 'ember-cli-htmlbars', |
| 35 | + }, |
| 36 | + }); |
| 37 | + |
| 38 | + // if no imports from 'ember-cli-htmlbars' exists, write import { hbs } from 'ember-cli-htmlbars'; |
| 39 | + if (emberCliImportStatement.length === 0) { |
| 40 | + const importStatement = j.importDeclaration([variableId], j.literal('ember-cli-htmlbars')); |
| 41 | + body.unshift(importStatement); |
| 42 | + } |
| 43 | + // if any imports from 'ember-cli-htmlbars' already exists, include hbs |
| 44 | + else { |
| 45 | + let existingSpecifiers = emberCliImportStatement.get('specifiers'); |
| 46 | + if (existingSpecifiers.filter(exSp => exSp.value.imported.name === hbs).length === 0) { |
| 47 | + existingSpecifiers.push(variableId); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments