ts-import-plugin
Version:
babel-plugin-import TypeScript version
193 lines • 8.15 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTransformer = void 0;
var ts = require("typescript");
var path_1 = require("path");
function join() {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
/* istanbul ignore if */
if (path_1.sep === '\\') {
var ret = path_1.join.apply(void 0, params);
return ret.replace(/\\/g, '/');
}
/* istanbul ignore next */
return path_1.join.apply(void 0, params);
}
// camel2Dash camel2Underline
// borrow from https://github.com/ant-design/babel-plugin-import
function camel2Dash(_str) {
var str = _str[0].toLowerCase() + _str.substr(1);
return str.replace(/([A-Z])/g, function ($1) { return "-".concat($1.toLowerCase()); });
}
function camel2Underline(_str) {
var str = _str[0].toLowerCase() + _str.substr(1);
return str.replace(/([A-Z])/g, function ($1) { return "_".concat($1.toLowerCase()); });
}
function getImportedStructs(node) {
var structs = new Set();
node.forEachChild(function (importChild) {
if (!ts.isImportClause(importChild)) {
return;
}
// not allow default import, or mixed default and named import
// e.g. import foo from 'bar'
// e.g. import foo, { bar as baz } from 'x'
// and must namedBindings exist
if (importChild.name || !importChild.namedBindings) {
return;
}
// not allow namespace import
// e.g. import * as _ from 'lodash'
if (!ts.isNamedImports(importChild.namedBindings)) {
return;
}
importChild.namedBindings.forEachChild(function (namedBinding) {
// ts.NamedImports.elements will always be ts.ImportSpecifier
var importSpecifier = namedBinding;
// import { foo } from 'bar'
if (!importSpecifier.propertyName) {
structs.add({ importName: importSpecifier.name.text });
return;
}
// import { foo as bar } from 'baz'
structs.add({
importName: importSpecifier.propertyName.text,
variableName: importSpecifier.name.text,
});
});
});
return structs;
}
function createDistAst(context, struct, options) {
var astNodes = [];
var libraryName = options.libraryName, libraryOverride = options.libraryOverride;
var _importName = struct.importName;
var importName = options.camel2UnderlineComponentName
? camel2Underline(_importName)
: options.camel2DashComponentName
? camel2Dash(_importName)
: _importName;
var libraryDirectory = typeof options.libraryDirectory === 'function'
? options.libraryDirectory(_importName)
: join(options.libraryDirectory || '', importName);
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production' && libraryDirectory == null) {
console.warn("custom libraryDirectory resolve a ".concat(libraryDirectory, " path"));
}
var importPath = !libraryOverride ? join(libraryName, libraryDirectory) : libraryDirectory;
var canResolveImportPath = true;
try {
require.resolve(importPath, {
paths: __spreadArray([process.cwd()], options.resolveContext, true),
});
}
catch (e) {
canResolveImportPath = false;
if (options.failIfNotFound) {
throw new Error("Can not find component for library: ".concat(options.libraryName, " in ").concat(importPath));
}
astNodes.push(context.factory.createImportDeclaration(undefined, context.factory.createImportClause(false, undefined, context.factory.createNamedImports([
context.factory.createImportSpecifier(false, undefined, context.factory.createIdentifier(_importName)),
])), context.factory.createStringLiteral(libraryName)));
}
if (canResolveImportPath) {
var scriptNode = context.factory.createImportDeclaration(undefined, context.factory.createImportClause(false, struct.variableName || !options.transformToDefaultImport
? undefined
: context.factory.createIdentifier(struct.importName), struct.variableName
? context.factory.createNamedImports([
context.factory.createImportSpecifier(false, options.transformToDefaultImport
? context.factory.createIdentifier('default')
: context.factory.createIdentifier(struct.importName), context.factory.createIdentifier(struct.variableName)),
])
: options.transformToDefaultImport
? undefined
: context.factory.createNamedImports([
context.factory.createImportSpecifier(false, undefined, context.factory.createIdentifier(struct.importName)),
])), context.factory.createStringLiteral(importPath));
astNodes.push(scriptNode);
if (options.style) {
var style = options.style;
var stylePath = void 0;
if (typeof style === 'function') {
stylePath = style(importPath);
}
else {
// eslint-disable-next-line no-restricted-syntax
stylePath = "".concat(importPath, "/style/").concat(style === true ? 'index' : style, ".js");
}
if (stylePath) {
var styleNode = context.factory.createImportDeclaration(undefined, undefined, context.factory.createStringLiteral(stylePath));
astNodes.push(styleNode);
}
}
}
return astNodes;
}
var defaultOptions = {
libraryName: 'antd',
libraryDirectory: 'lib',
style: false,
camel2DashComponentName: true,
camel2UnderlineComponentName: false,
transformToDefaultImport: true,
resolveContext: [],
libraryOverride: false,
failIfNotFound: false,
};
function createTransformer(_options) {
if (_options === void 0) { _options = {}; }
var mergeDefault = function (options) { return (__assign(__assign({}, defaultOptions), options)); };
var optionsArray = Array.isArray(_options)
? _options.map(function (options) { return mergeDefault(options); })
: [mergeDefault(_options)];
return function (context) {
var visitor = function (node) {
if (ts.isSourceFile(node)) {
return ts.visitEachChild(node, visitor, context);
}
if (!ts.isImportDeclaration(node)) {
return node;
}
var importedLibName = node.moduleSpecifier.text;
var options = optionsArray.find(function (_) { return _.libraryName === importedLibName; });
if (!options) {
return node;
}
var structs = getImportedStructs(node);
if (structs.size === 0) {
return node;
}
return Array.from(structs).reduce(function (acc, struct) {
var nodes = createDistAst(context, struct, options);
return acc.concat(nodes);
}, []);
};
return function (node) { return ts.visitNode(node, visitor); };
};
}
exports.createTransformer = createTransformer;
exports.default = createTransformer;
//# sourceMappingURL=index.js.map
;