-
Notifications
You must be signed in to change notification settings - Fork 33
/
babel-plugin-relative-import.js
66 lines (61 loc) · 2.63 KB
/
babel-plugin-relative-import.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @file change import name to relative path
* @author meixuguang
*/
/* eslint-disable fecs-no-require */
const path = require('path');
const {getModuleName} = require('../../helper/path');
const {getModulePath} = require('./compileModules');
module.exports = function ({types: t}) {
return {
visitor: {
ImportDeclaration(babelPath, state) {
const {rPath, modules, usedModules = {}, compileNPM = false} = state.opts;
const name = babelPath.node.source.value;
const modName = getModuleName(name);
if (modName && (compileNPM || modules[modName])) {
let modulePath = getModulePath(name, modules).replace(/\.js$/, '');
let relativePath = path.join(rPath, modulePath);
if (relativePath[0] !== '.') {
relativePath = './' + relativePath;
}
const resolvedPath = name.replace(modName, relativePath);
usedModules[name] = {
modName,
path: modulePath,
resolvedPath
};
babelPath.node.source.value = resolvedPath;
}
},
CallExpression(nodePath, state) {
const node = nodePath.node;
const callee = node.callee;
const arg = node.arguments[0];
if (callee.type !== 'Identifier' || callee.name !== 'require' || !arg || arg.type !== 'StringLiteral') {
return;
}
const {rPath, modules, usedModules = {}, compileNPM = false} = state.opts;
const name = arg.value;
const modName = getModuleName(name);
if (modName && (compileNPM || modules[modName])) {
let modulePath = getModulePath(name, modules).replace(/\.js$/, '');
let relativePath = path.join(rPath, modulePath);
if (relativePath[0] !== '.') {
relativePath = './' + relativePath;
}
const resolvedPath = name.replace(modName, relativePath);
usedModules[name] = {
modName,
path: modulePath,
resolvedPath
};
nodePath.replaceWith(
t.callExpression(callee, [t.stringLiteral(resolvedPath)])
);
// babelPath.node.source.value = resolvedPath;
}
}
}
};
};