Skip to content

Commit

Permalink
fix webpack alias bug
Browse files Browse the repository at this point in the history
  • Loading branch information
FogelAI committed May 21, 2024
1 parent 9c0ea8f commit 16408cb
Showing 1 changed file with 93 additions and 89 deletions.
182 changes: 93 additions & 89 deletions src/alias.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,47 @@ const ospath = require("path");
const fg = require("fast-glob");
const PathFunctions = require("./path");

class PackageJson {
constructor() {
this.mainPkg = ospath.resolve('package.json');
this.packagesJsons = [];
class Workspaces {
constructor(path) {
this.path = path || ospath.resolve('package.json');
this.data = {};
this.aliasObj = {};
this.workspaces = this.loadWorkspaces();
this.getNodePackages();
this.aliasesToWorkspaces();
}

loadWorkspaces() {
const workspaces = require(this.mainPkg).workspaces || [];
loadPackageJson() {
this.data = require(this.path);
}

load() {
this.loadPackageJson();
this.workspacesToAliases()
}

get workspaces() {
const workspaces = this.data.workspaces || [];
if (Array.isArray(workspaces)) return workspaces;
return workspaces.packages || [];
}

getNodePackages( { workspacePath = ospath.resolve('.') } = {} ) {
if (this.workspaces===[]) return [];
const globWorkspaces = this.workspaces.map((ws)=> ws + '/**/package.json');
getWorkspacesPackageJsons( { startPath = ospath.resolve('.'), workspaces } = {} ) {
const globWorkspaces = workspaces.map((ws)=> ws + '/**/package.json');
const packagesJsons = fg.sync(
globWorkspaces,
{
deep: Infinity,
onlyFiles: true,
absolute: true,
cwd: workspacePath,
cwd: startPath,
ignore: ['**/node_modules'],
},
);
this.packagesJsons = packagesJsons;
return packagesJsons;
}

aliasesToWorkspaces() {
const aliases = this.packagesJsons.reduce((alias, pkgPath) => {
workspacesToAliases() {
const { workspaces } = this;
const packagesJsons = this.getWorkspacesPackageJsons({workspaces});
const aliases = packagesJsons.reduce((alias, pkgPath) => {
const pkgName = require(pkgPath).name;
alias[pkgName] = ospath.dirname(pkgPath);
return alias;
Expand All @@ -50,100 +56,98 @@ class PackageJson {
}
}

class WebpackConfig {
constructor() {
class AliasWebpack {
constructor(options) {
this.path = options.webpackConfigFilename;
this.args = options.args || [];
this.data = {};
this.aliasObj = {};
}

getWebpackAlias(plugin) {
const filePath = plugin.options.webpackConfigFilename;
// If the config comes back as null, we didn't find it, so throw an exception.
if (!filePath) {
return null;
}
const webpackConfigObj = require(filePath);

let alias = {};

resolveWebpackConfig() {
const webpackConfigObj = require(this.path);
if (typeof webpackConfigObj === 'object') {
if (!PathFunctions.isObjectEmpty(webpackConfigObj?.resolve?.alias)) {
alias = webpackConfigObj.resolve.alias;
}
this.data = webpackConfigObj;
} else if (typeof webpackConfigObj === 'function') {
const args = plugin.options.args || [];
alias = webpackConfigObj(...args).resolve.alias;
this.data = webpackConfigObj(...this.args);
}
this.aliasObj = alias;
return alias;
}

convertAliasToOriginal(parsedJSFile, originalImportsPath) {
let convertedPath = originalImportsPath;
const aliasObj = this.aliasObj;
const aliases = Object.keys(aliasObj);
}

load() {
if (!this.path) return;
this.resolveWebpackConfig();
this.aliasObj = this.data?.resolve?.alias || {};
this.addPrefixRegexToAliases();
}

addPrefixRegexToAliases() {
if (PathFunctions.isObjectEmpty(this.aliasObj)) return;
const newAliasObj = {};
const aliases = Object.keys(this.aliasObj);
for (const alias of aliases) {
let aliasDestination = aliasObj[alias];
const regex = new RegExp(`^${alias}(\/|$)`);

if (regex.test(originalImportsPath)) {
const isModule = PathFunctions.checkIfModule(aliasDestination);
if (isModule) {
convertedPath = aliasDestination;
break;
}
// If the filepath is not absolute, make it absolute
if (!ospath.isAbsolute(aliasDestination)) {
aliasDestination = ospath.join(ospath.dirname(parsedJSFile), aliasDestination);
}
let relativeFilePath = ospath.relative(ospath.dirname(parsedJSFile), aliasDestination);

// In case the file path is the root of the alias, need to put a dot to avoid having an absolute path
if (relativeFilePath.length === 0) {
relativeFilePath = '.';
}

let requiredFilePath = originalImportsPath.replace(regex, relativeFilePath);

// If the file is requiring the current directory which is the alias, add an extra slash
if (requiredFilePath === '.') {
requiredFilePath = './';
}

// In the case of a file requiring a child directory of the current directory, we need to add a dot slash
if (['.', '/'].indexOf(requiredFilePath[0]) === -1) {
requiredFilePath = `./${requiredFilePath}`;
}

convertedPath = requiredFilePath;
break;
}
newAliasObj[`^${alias}`] = this.aliasObj[alias];
}
return convertedPath;
this.aliasObj = newAliasObj;
return newAliasObj;
}

getAlias() {
return this.aliasObj;
}

appendAlias(alias) {
this.aliasObj = { ...this.aliasObj, ...alias };
}
}

class JestConfig {
constructor() {
this.aliasObj = {};
class AliasJest {
constructor(options) {
this.aliasObj = options.jestAlias || {};
}

getJestAlias(plugin) {
const aliases = plugin.options.jestAlias;
if (!aliases) {
return null;
}
aliases.forEach((alias)=>{
this.aliasObj[alias[0]] = alias[1];
load() {
if (PathFunctions.isObjectEmpty(this.aliasObj)) return;
this.buildAliasMap();
}

buildAliasMap() {
if (PathFunctions.isObjectEmpty(this.aliasObj)) return;
const newAliasObj = {};
this.aliasObj.forEach((alias)=>{
newAliasObj[alias[0]] = alias[1];
})
this.aliasObj = newAliasObj;
return this.aliasObj;
}


getAlias() {
return this.aliasObj;
}

appendAlias(alias) {
this.aliasObj = { ...this.aliasObj, ...alias };
}
}

module.exports = { PackageJson, WebpackConfig, JestConfig }
class AliasFactory {
static createAlias(type, options) {
switch (type) {
case 'workspaces':
const workspaces = new Workspaces();
workspaces.load();
return workspaces;
case 'webpack':
const webpack = new AliasWebpack(options);
webpack.load();
return webpack;
case 'jest':
const jest = new AliasJest(options);
jest.load();
return jest;
default:
throw new Error('Invalid alias type');
}
}
}

module.exports = AliasFactory;

0 comments on commit 16408cb

Please sign in to comment.