Last active
May 8, 2018 15:58
-
-
Save maddrag0n/196c478bb4ecae0a0b36a0b6a8b098e7 to your computer and use it in GitHub Desktop.
Reads babelrc module-resolver aliases and convert to aliases for webpack
This file contains 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
const fs = require('fs'); | |
const path = require('path'); | |
/** | |
* Reads babelrc module-resolver aliases and convert to aliases for webpack | |
* | |
* @prop {string} babelrcPath - path to .babelrc | |
* @return {object} - webpack alias object | |
* @author maddrag0n // (https://github.com/maddrag0n) | |
* @license BSD-3-Clause - https://opensource.org/licenses/BSD-3-Clause | |
*/ | |
const transform = (babelrcPath) => { | |
// read babelrc | |
const { plugins } = JSON.parse(fs.readFileSync(babelrcPath, { encoding: 'utf8' })); | |
// get moduleResolverPlugin config | |
const moduleResolverPlugin = (plugins || []).filter(c => Array.isArray(c)) | |
.find(c => c[0].toLowerCase() === 'module-resolver') || []; | |
// get alias property | |
const { alias: aliasCandidate, root: rootCandidate } = (moduleResolverPlugin[1] || {}); | |
const alias = aliasCandidate || {}; | |
// normalize root config | |
const root = Array.isArray(rootCandidate) | |
? rootCandidate | |
: [ rootCandidate || './' ]; | |
// flatten root config | |
const rootPath = !root.length | |
? '' | |
: root.filter(c => Boolean(c.replace('./', ''))) | |
.reduce((acc, partial) => path.join(acc, partial), ''); | |
// resolve cwd with root config | |
const cwd = path.dirname(path.resolve(babelrcPath)); | |
const rootDir = path.join(cwd, rootPath); | |
// transform babelrc alias to webpack resolve alias | |
const transformed = Object.keys(alias) | |
.reduce((acc, key) => { | |
const value = alias[key]; | |
if (value.startsWith('.')) { | |
acc[key] = path.join(rootDir, value); | |
} else { | |
acc[key] = value; | |
} | |
return acc; | |
}, {}); | |
return transformed; | |
}; | |
module.exports = transform; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment