Skip to content

Commit 12bcc15

Browse files
committed
refactor plugin options
1 parent 8aec22a commit 12bcc15

File tree

10 files changed

+42
-67
lines changed

10 files changed

+42
-67
lines changed

README.md

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
This Babel plugin transforms indirect imports through a barrel file (index.js) into direct imports.
77

88
### Note
9-
This plugin is intended for developers who use barrel files (index.js) with dynamic imports and/or CSS imports in their code when using the Webpack bundler or Jest. I don't know if it's needed to use in other bundlers such as Parcel, Rollup Vite and etc.
9+
This plugin is intended for developers who use barrel files (index.js) with the Webpack or Vite bundlers, or when running tests with Jest. I don't know if it's beneficial to use with other bundlers such as Parcel, Rollup, etc.
1010

1111
## Example
1212

@@ -59,16 +59,13 @@ import { List } from './components/List/List'
5959

6060
## Options
6161

62-
| **Name** | **Type** | **Default** | **Description** |
63-
|:-------------------:|:---------:|:---------------------------------------------------------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
64-
| `webpackAlias` | `object` | `{}` | It should be assigned with the `alias` value option from the Webpack config. |
65-
| `viteAlias` | `object` | `{}` | It should be assigned with the `alias` value option from the Vite config. |
66-
| `jestAlias` | `array` | `[]` | It should be assigned with the `moduleNameMapper` value option from the Jest config. |
67-
| `webpackExtensions` | `array` | `[".js", ".jsx", ".ts", ".tsx"]` | It should be assigned with the `extensions` value option from the Webpack config. |
68-
| `viteExtensions` | `array` | `[".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]` | It should be assigned with the `extensions` value option from the Vite config. |
69-
| `jestExtensions` | `array` | `["js", "jsx", "ts", "tsx"]` | It should be assigned with the `moduleFileExtensions` value option from the Jest config. |
70-
| `isCacheEnabled` | `boolean` | `false` | If `true`, enables file-based cache. |
71-
| `logging` | `object` | `{ type: "disabled", filePath: "log.txt" }` | Specifies logging options.<br>`type` can be `disabled` for no logging, `file` for logs to a file, or `screen` for logs to the console.<br>If type is `file`, `filePath` specifies the log file path. |
62+
| **Name** | **Type** | **Default** | **Description** |
63+
|:----------------:|:---------:|:------------------------------------------------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
64+
| `executorName` | `string` | `"other"` | It should be assigned with one of the supported executor values: `webpack`, `vite` or `jest`. |
65+
| `alias` | `object` | `{}` | It should be assigned with the `alias` value option from the executor config. |
66+
| `extensions` | `array` | `[".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"]` | It should be assigned with the `extensions` value option from the executor config. |
67+
| `isCacheEnabled` | `boolean` | `false` | If `true`, enables file-based cache. |
68+
| `logging` | `object` | `{ type: "disabled", filePath: "log.txt" }` | Specifies logging options.<br>`type` can be `disabled` for no logging, `file` for logs to a file, or `screen` for logs to the console.<br>If type is `file`, `filePath` specifies the log file path. |
7269

7370
## The Problem
7471

config/jest/babelTransform.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ module.exports = {
66
const extensions = options.config.moduleFileExtensions;
77
const babelTransformer = babelJest.createTransformer({
88
presets: [["@babel/preset-react"], ["@babel/preset-env"]],
9-
plugins: [["transform-barrels", { jestAlias: alias, jestExtensions: extensions }]],
9+
plugins: [["transform-barrels", { executorName: "jest", alias: alias, extensions: extensions }]],
1010
babelrc: false,
1111
configFile: false,
1212
});

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "babel-plugin-transform-barrels",
3-
"version": "1.0.15",
3+
"version": "1.0.16",
44
"description": "A Babel plugin that transforms indirect imports through a barrel file (index.js) into direct imports.",
55
"homepage": "https://github.com/FogelAI/babel-plugin-transform-barrels",
66
"main": "src/main.js",

src/executorConfig.js

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,17 @@ class Workspaces {
5858

5959
class ExecutorConfig {
6060
constructor(alias, extensions, loadStrategy) {
61-
this.alias = alias || [];
61+
this.alias = alias || {};
6262
this.extensions = extensions || [];
6363
this.loadStrategy = loadStrategy;
6464
}
6565

6666
load() {
67-
this.alias = this.loadStrategy.prepareAlias(this.alias)
68-
this.extensions = this.loadStrategy.prepareExtensions(this.extensions)
67+
if (this.loadStrategy) {
68+
this.alias = this.loadStrategy.prepareAlias(this.alias)
69+
this.extensions = this.loadStrategy.prepareExtensions(this.extensions)
70+
}
71+
this.addWorkspacesToAlias();
6972
}
7073

7174
getAlias() {
@@ -75,6 +78,15 @@ class ExecutorConfig {
7578
getExtensions() {
7679
return this.extensions;
7780
}
81+
82+
addWorkspacesToAlias() {
83+
const workspaces = new Workspaces();
84+
workspaces.load();
85+
this.alias = {
86+
...workspaces.getAlias(),
87+
...this.getAlias()
88+
}
89+
}
7890
}
7991

8092
class WebpackStrategy {
@@ -109,11 +121,11 @@ class ViteStrategy {
109121

110122
class JestStrategy {
111123
prepareExtensions(extensions) {
112-
return extensions.map(ext => `.${ext}`);
124+
return extensions.map(ext => ext.startsWith(".") ? ext : `.${ext}`);
113125
}
114126

115127
prepareAlias(alias) {
116-
return Object.fromEntries(alias);
128+
return Array.isArray(alias) ? Object.fromEntries(alias) : alias;
117129
}
118130
}
119131

@@ -132,12 +144,9 @@ class ExecutorFactory {
132144
const jest = new ExecutorConfig(alias, extensions, new JestStrategy());
133145
jest.load();
134146
return jest;
135-
case 'workspaces':
136-
const workspaces = new Workspaces();
137-
workspaces.load();
138-
return workspaces;
139147
default:
140148
const defaultExecutor = new ExecutorConfig();
149+
defaultExecutor.load();
141150
return defaultExecutor;
142151
}
143152
}

src/main.js

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const importDeclarationVisitor = (path, state) => {
1313
if (AST.getSpecifierType(importsSpecifiers[0]) === "namespace") return;
1414
const parsedJSFile = state.filename;
1515
const importsPath = path.node.source.value;
16-
if (importsPath.startsWith("/") || importsPath.startsWith("\\")) return;
16+
if (pluginOptions.options.executorName === "vite" && importsPath.startsWith("/")) return;
1717
if (builtinModules.includes(importsPath)) return;
1818
logger.log(`Source import line: ${generate(path.node, { comments: false, concise: true }).code}`);
1919
resolver.from = parsedJSFile;
@@ -44,22 +44,8 @@ module.exports = function (babel) {
4444
const { options } = pluginOptions;
4545
logger.setOptions(options.logging);
4646
logger.log(`Processed Javascript file: ${state.opts.filename}`);
47-
const workspaces = ExecutorFactory.createExecutor("workspaces");
48-
let executor;
49-
if (pluginOptions.executorName === "webpack") {
50-
executor = ExecutorFactory.createExecutor("webpack", options.webpackAlias, options.webpackExtensions);
51-
} else if (pluginOptions.executorName === "vite") {
52-
executor = ExecutorFactory.createExecutor("vite", options.viteAlias, options.viteExtensions);
53-
} else if (pluginOptions.executorName === "jest") {
54-
executor = ExecutorFactory.createExecutor("jest", options.jestAlias, options.jestExtensions);
55-
} else {
56-
executor = ExecutorFactory.createExecutor();
57-
}
58-
const alias = {
59-
...workspaces.getAlias(),
60-
...executor.getAlias()
61-
}
62-
resolver.appendAlias(alias);
47+
const executor = ExecutorFactory.createExecutor(options.executorName, options.alias, options.extensions);
48+
resolver.appendAlias(executor.getAlias());
6349
const extensions = executor.getExtensions();
6450
extensions.length !==0 && resolver.setExtensions(extensions)
6551
},

src/pluginOptions.js

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,10 @@ let instance;
22

33
class PluginOptions {
44
constructor() {
5-
this.executorName = "";
65
this.options = {
7-
webpackAlias: {},
8-
webpackExtensions: [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"],
9-
viteAlias: {},
10-
viteExtensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"],
11-
jestAlias: [],
12-
jestExtensions: ["js", "jsx", ".mjs", ".cjs", "ts", "tsx"],
6+
executorName: "other",
7+
alias: {},
8+
extensions: [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"],
139
isCacheEnabled: false,
1410
logging: {
1511
type: "disabled",
@@ -23,24 +19,11 @@ class PluginOptions {
2319
}
2420

2521
setOptions(options) {
26-
this.executorName = this.getExecutorName(options);
2722
this.options= {
2823
...this.options,
2924
...options
3025
};
3126
}
32-
33-
getExecutorName(options) {
34-
if (options.webpackAlias || options.webpackExtensions) {
35-
return "webpack";
36-
} else if (options.viteAlias || options.viteExtensions) {
37-
return "vite";
38-
} else if (options.jestAlias || options.jestExtensions) {
39-
return "jest";
40-
} else {
41-
return "";
42-
}
43-
}
4427
}
4528

4629
const singletonPluginOptions = new PluginOptions();

tests/js/ant-design/ant-design-cjs/ant-design-cjs.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ describe("third-party package (@ant-design/icons) transformation for CommonJS",
1919
const alias = {
2020
icons: "@ant-design/icons",
2121
}
22-
const pluginOptions = { webpackAlias: alias, isCacheEnabled: true };
22+
const pluginOptions = { executorName: "webpack", alias: alias, isCacheEnabled: true };
2323
expect(
2424
pluginTransform(
2525
'import { ZoomInOutlined } from "icons";',

tests/js/local/imports.test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ describe("aliases", () => {
6060
const alias = {
6161
components: ospath.resolve(__dirname, 'components'),
6262
}
63-
const pluginOptions = { webpackAlias: alias };
63+
const pluginOptions = { executorName: "webpack", alias: alias };
6464
expect(
6565
pluginTransform(
6666
'import { Text } from "components/Texts";',
@@ -76,7 +76,7 @@ describe("aliases", () => {
7676
const alias = {
7777
components: ospath.resolve(__dirname, 'components'),
7878
}
79-
const pluginOptions = { viteAlias: alias };
79+
const pluginOptions = { executorName: "vite", alias: alias };
8080
expect(
8181
pluginTransform(
8282
'import { Text } from "components/Texts";',
@@ -92,7 +92,7 @@ describe("aliases", () => {
9292
const alias = Object.entries({
9393
"^abc/(.*)$": "./components/$1"
9494
});
95-
const pluginOptions = { jestAlias: alias };
95+
const pluginOptions = { executorName: "jest", alias: alias };
9696
expect(
9797
pluginTransform(
9898
'import { Text } from "abc/Texts";',

tests/js/mui/mui-cjs/mui-cjs.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ describe("third-party package (@mui/icons-material) transformation for CommonJS"
1919
const alias = {
2020
icons: "@mui/icons-material",
2121
}
22-
const pluginOptions = { webpackAlias: alias, isCacheEnabled: true };
22+
const pluginOptions = { executorName: "webpack", alias: alias, isCacheEnabled: true };
2323
expect(
2424
pluginTransform(
2525
'import { ZoomIn } from "icons";',

tests/ts/local/imports.test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const ospath = require("path");
44
describe('typescript transformation', () => {
55
test("transformation of a named import - jest", () => {
66
const extensions = ["ts", "tsx"];
7-
const pluginOptions = { jestExtensions: extensions };
7+
const pluginOptions = { executorName: "jest", extensions: extensions };
88
expect(
99
pluginTransform(
1010
'import {namedExport} from "./components";',
@@ -18,7 +18,7 @@ describe('typescript transformation', () => {
1818

1919
test("transformation of a named import - vite", () => {
2020
const extensions = [".ts", ".tsx"];
21-
const pluginOptions = { viteExtensions: extensions };
21+
const pluginOptions = { executorName: "vite", extensions: extensions };
2222
expect(
2323
pluginTransform(
2424
'import {namedExport} from "./components";',
@@ -32,7 +32,7 @@ describe('typescript transformation', () => {
3232

3333
test("transformation of a named import that was originally re-exported from a default export in the barrel file - webpack", () => {
3434
const extensions = [".ts", ".tsx"];
35-
const pluginOptions = { webpackExtensions: extensions };
35+
const pluginOptions = { executorName: "webpack", extensions: extensions };
3636
expect(
3737
pluginTransform(
3838
'import {defaultExport} from "./components";',

0 commit comments

Comments
 (0)