All files / lib plugin.js

100% Statements 20/20
100% Branches 10/10
100% Functions 3/3
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40    7x 7x           7x 11x       32x 32x   31x 31x 31x 12x   12x 22x   22x 19x 34x     19x       12x          
"use strict";
 
const PluginOptions = require("./internal/PluginOptions");
const DependencyTree = require("./internal/DependencyTree");
 
/**
 * @param {import("@babel/core")} babel
 * @returns {import("@babel/core").PluginObj}
 */
module.exports = function plugin(babel) {
  return {
    name: "babel-plugin-direct-import",
    visitor: {
      ImportDeclaration(declaration, { opts }) {
        const { source, specifiers, importKind } = declaration.node;
        if (!specifiers.length || importKind === "type") return;
 
        const pluginOptions = PluginOptions.parse(opts);
        const nodeModule = pluginOptions.modules.get(source.value);
        if (!nodeModule) return;
        const tree = DependencyTree.create(nodeModule, babel);
 
        for (const specifier of specifiers) {
          const replacement = tree.process(specifier);
 
          if (replacement) {
            declaration.node.specifiers = declaration.node.specifiers.filter(
              (x) => x !== specifier
            );
 
            declaration.insertBefore(replacement);
          }
        }
 
        if (!declaration.node.specifiers.length) declaration.remove();
      },
    },
  };
};