babel-plugin-transform-remove-imports
Version:
Remove the specified import declaration when you use the babel transform to build the package.
83 lines (77 loc) • 2.44 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = _default;
function _default() {
return {
name: 'transform-remove-imports',
visitor: {
// https://babeljs.io/docs/en/babel-types#callexpression
CallExpression: function CallExpression(path, state) {
var node = path.node;
if (node.callee.name !== 'require') {
return;
}
var argument = node.arguments[0];
var moduleId = argument.value;
var options = state.opts;
if (options.test && !testMatches(moduleId, options.test)) {
return;
}
var parentType = path.parentPath.node.type;
// In remove effects mode we should delete only requires that are
// simple expression statements
if (options.remove === 'effects' && parentType !== 'ExpressionStatement') {
return;
}
path.remove();
},
// https://babeljs.io/docs/en/babel-types#importdeclaration
ImportDeclaration: function ImportDeclaration(path, state) {
var node = path.node;
var source = node.source;
var opts = state.opts;
if (opts.removeAll) {
path.remove();
return;
}
if (!opts.test) {
console.warn('transform-remove-imports: "test" option should be specified');
return;
}
/** @var {string} importName */
var importName = source && source.value ? source.value : undefined;
var isMatch = testMatches(importName, opts.test);
// https://github.com/uiwjs/babel-plugin-transform-remove-imports/issues/3
if (opts.remove === 'effects') {
if (node.specifiers && node.specifiers.length === 0 && importName && isMatch) {
path.remove();
}
return;
}
if (importName && isMatch) {
path.remove();
}
}
}
};
}
/**
* Determines if the import matches the specified tests.
*
* @param {string} importName
* @param {RegExp|RegExp[]|string|string[]} test
* @returns {Boolean}
*/
function testMatches(importName, test) {
// Normalizing tests
var tests = Array.isArray(test) ? test : [test];
// Finding out if at least one test matches
return tests.some(function (regex) {
if (typeof regex === 'string') {
regex = new RegExp(regex);
}
return regex.test(importName || '');
});
}
;