Created
April 3, 2018 23:15
-
-
Save HenryNguyen5/e4d88596f59738a991da5adc15877f8e to your computer and use it in GitHub Desktop.
alias-resolver for path-alias-resolver package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
Object.defineProperty(exports, '__esModule', { value: true }); | |
const { resolvePath } = require('babel-plugin-module-resolver'); | |
class AliasResolver { | |
constructor(root, aliases = {}) { | |
this.aliases = {}; | |
this.rule = /(?:require|import)[^'"]*(?:'|")([^'"]*)(?:'|")/g; | |
this.parseLine = (line, filePath) => { | |
const transformedLine = line.replace(this.rule, (substr, moduleId) => { | |
// console.log('matched ', line); | |
let relativeModule = resolvePath(moduleId, filePath, { | |
root: this.root, | |
alias: this.aliases, | |
}); | |
// console.log(relativeModule); | |
if (!relativeModule) { | |
return substr; | |
} | |
// relativeModule = relativeModule.replace('../', ''); | |
return substr.replace(moduleId, relativeModule); | |
}); | |
return transformedLine; | |
}; | |
this.root = root; | |
this.aliases = aliases; | |
} | |
static create(root, aliases = {}) { | |
return new AliasResolver(root, aliases); | |
} | |
resolve(filePath, content) { | |
let lines = content.split('\n'); | |
lines = joinImports(lines); | |
lines = lines.map(line => this.parseLine(line, filePath)); | |
return lines.join('\n'); | |
} | |
} | |
function joinImports(lines) { | |
const returnArr = []; | |
let foundMultiLineImport = false; | |
for (const line of lines) { | |
const singleLineRule = /(?:require|import)[^'"]*(?:'|")([^'"]*)(?:'|")/g; | |
const multiLineRule = { b: /^import {/, e: /^} from '.*';$/ }; | |
if (foundMultiLineImport) { | |
returnArr[returnArr.length - 1] += line; | |
} else { | |
returnArr.push(line); | |
} | |
if (line.match(multiLineRule.e)) { | |
foundMultiLineImport = false; | |
returnArr[returnArr.length - 1].replace('\\', ''); | |
} | |
if (!line.match(singleLineRule) && line.match(multiLineRule.b)) { | |
foundMultiLineImport = true; | |
} | |
} | |
return returnArr; | |
} | |
exports.AliasResolver = AliasResolver; | |
//# sourceMappingURL=alias-resolver.js.map |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment