Skip to content

Commit

Permalink
bugfix
Browse files Browse the repository at this point in the history
  • Loading branch information
indooorsman committed Mar 17, 2022
1 parent e4f0859 commit b028a20
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
25 changes: 21 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@ const fs = require('fs');
const path = require('path');
const extensions = ['js', 'jsx', 'ts', 'tsx', 'cjs', 'mjs', 'cjsx', 'mjsx'];

const readFromPackage = (dir) => {
const manifestFile = path.resolve(dir, './package.json');
let isExisted = true;
try {
fs.accessSync(manifestFile, fs.constants.F_OK);
} catch (e) {
isExisted = false;
}
if (!isExisted) {
return dir;
}
const detail = JSON.parse(fs.readFileSync(manifestFile, {encoding: 'utf8'}))
const entry = detail.module || detail.main;
return path.resolve(dir, entry);
};

const patchExtension = (p) => {
let isExisted = true;
try {
Expand Down Expand Up @@ -45,6 +61,7 @@ const patchExtension = (p) => {
if (ext) {
return path.resolve(p, `./index.${ext}`);
}
return readFromPackage(p);
}
return p;
};
Expand Down Expand Up @@ -79,8 +96,8 @@ const aliasPlugin = (config) => {
const targetPath = config[k].replace(/\/$/, '');
const patchedPath = patchExtension(
args.path
.replace(new RegExp(`^${k}\\/`), targetPath + '/')
.replace(new RegExp(`^${k}$`), targetPath)
.replace(new RegExp(`^.*${k}\\/`), targetPath + '/')
.replace(new RegExp(`^.*${k}$`), targetPath)
);
outputLogs && console.log(
`${new Date().toLocaleTimeString()} [plugin-path-alias] `,
Expand All @@ -94,10 +111,10 @@ const aliasPlugin = (config) => {
};

alias.forEach((k) => {
build.onResolve({ filter: new RegExp(`^${k}$`) }, (args) => {
build.onResolve({ filter: new RegExp(`^.*${k}$`) }, (args) => {
return main(k, args);
});
build.onResolve({ filter: new RegExp(`^${k}\\/.*$`) }, (args) => {
build.onResolve({ filter: new RegExp(`^.*${k}\\/.*$`) }, (args) => {
return main(k, args);
});
});
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "esbuild-plugin-path-alias",
"version": "1.0.5",
"version": "1.0.6",
"description": "A esbuild plugin to support path alias like `resolve.alias` in webpack config.",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit b028a20

Please sign in to comment.