Skip to content

Commit

Permalink
Adds support for babel-module-resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
leorossi committed Feb 19, 2020
1 parent f02e589 commit 5daaae9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
"yargs": "^14.2.0"
},
"devDependencies": {
"babel-plugin-module-resolver": "^4.0.0",
"eslint": "^6.6.0",
"eslint-config-prettier": "^6.5.0",
"eslint-plugin-prettier": "^3.1.1",
"find-babel-config": "^1.2.0",
"husky": "^3.0.9",
"lint-staged": "^9.4.2",
"prettier": "^1.18.2"
Expand Down
30 changes: 28 additions & 2 deletions src/handlers/fileResolver.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
const path = require("path");
const enhancedResolve = require("enhanced-resolve");
const { defaultParsableExtensions } = require("../models/Parsables");

const moduleResolver = require("babel-plugin-module-resolver");
const findBabelConfig = require("find-babel-config");
function checkNodeModules(absPath) {
return /node_modules/.test(absPath) || (absPath[0] !== "/" && absPath[1] !== ':');
return (
/node_modules/.test(absPath) || (absPath[0] !== "/" && absPath[1] !== ":")
);
}

function checkBabelModuleResolver(filePath, currentFile) {
const loadedConfig = findBabelConfig.sync(currentFile);
if (loadedConfig) {
// find module-resolver configuration
const moduleResolverConfig = loadedConfig.config.plugins.find(element => {
if (Array.isArray(element)) {
if (element[0] == "module-resolver") {
return element;
}
}
});
const opts = moduleResolverConfig[1];
const currentFileDirectory = path.dirname(currentFile);
const resolved = moduleResolver.resolvePath(filePath, currentFile, opts);
const output = path.join(currentFileDirectory, resolved);
return output;
}
}
// by default resolve Parsable files even without .ext in import
const resolveSync = enhancedResolve.create.sync({
extensions: defaultParsableExtensions
Expand All @@ -18,6 +39,10 @@ const resolveSync = enhancedResolve.create.sync({
*/
function resolve(relPath = "", currentFile = "") {
const currentDir = path.dirname(currentFile);
if (!relPath.match(/^(\.|\/)/)) {
// path doesn't start with a '.' or with a '/' which should be local dependencies
relPath = checkBabelModuleResolver(relPath, currentFile);
}

try {
const absPath = resolveSync(currentDir, relPath);
Expand All @@ -27,6 +52,7 @@ function resolve(relPath = "", currentFile = "") {
return { resolved };
} catch (err) {
if (!err.missing) return;

const notFound = checkNodeModules(relPath)
? relPath
: path.resolve(currentDir, relPath);
Expand Down

0 comments on commit 5daaae9

Please sign in to comment.