UNPKG

@ianvs/prettier-plugin-sort-imports

Version:

A prettier plugins to sort imports in provided RegEx order

62 lines (61 loc) 2.93 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCodeFromAst = void 0; const generator_1 = __importDefault(require("@babel/generator")); const types_1 = require("@babel/types"); const constants_1 = require("../constants"); const get_all_comments_from_nodes_1 = require("./get-all-comments-from-nodes"); const remove_nodes_from_original_code_1 = require("./remove-nodes-from-original-code"); /** * This function generates a code string from the passed nodes. * @param nodesToOutput The remaining imports which should be rendered. (Node specifiers & types may be mutated) * @param allOriginalImportNodes All import nodes that were originally relevant. (This includes nodes that need to be deleted!) * @param originalCode The original input code that was passed to this plugin. * @param directives All directive prologues from the original code (e.g. * `"use strict";`). * @param interpreter Optional interpreter directives, if present (e.g. * `#!/bin/node`). */ const getCodeFromAst = ({ nodesToOutput, allOriginalImportNodes = nodesToOutput, originalCode, directives, interpreter, }) => { const allCommentsFromImports = (0, get_all_comments_from_nodes_1.getAllCommentsFromNodes)(nodesToOutput); const allCommentsFromDirectives = (0, get_all_comments_from_nodes_1.getAllCommentsFromNodes)(directives); const allCommentsFromInterpreter = interpreter ? (0, get_all_comments_from_nodes_1.getAllCommentsFromNodes)([interpreter]) : []; const nodesToRemoveFromCode = [ ...nodesToOutput, ...allOriginalImportNodes, ...allCommentsFromImports, ...allCommentsFromDirectives, ...allCommentsFromInterpreter, ...(interpreter ? [interpreter] : []), ...directives, ]; const codeWithoutImportsAndInterpreter = (0, remove_nodes_from_original_code_1.removeNodesFromOriginalCode)(originalCode, nodesToRemoveFromCode); const newAST = (0, types_1.file)({ type: 'Program', body: nodesToOutput, directives: directives, sourceType: 'module', interpreter: interpreter, leadingComments: [], innerComments: [], trailingComments: [], start: 0, end: 0, loc: { start: { line: 0, column: 0, index: 0 }, end: { line: 0, column: 0, index: 0 }, filename: '', identifierName: '', }, }); const { code } = (0, generator_1.default)(newAST, { importAttributesKeyword: 'with' }); const replacedCode = code.replace(constants_1.injectNewlinesRegex, constants_1.newLineCharacters); const trailingCode = codeWithoutImportsAndInterpreter.trim(); return replacedCode + trailingCode; }; exports.getCodeFromAst = getCodeFromAst;