Skip to content

Commit c9de5c9

Browse files
committed
Init
0 parents  commit c9de5c9

File tree

4 files changed

+267
-0
lines changed

4 files changed

+267
-0
lines changed

README.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# babel-plugin-transform-barrels
2+
This Babel plugin transforms indirect imports through a barrel file (index.js) into direct imports.
3+
4+
### Note
5+
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. I don't know if it's needed to use in other bundlers such as Parcel, Rollup Vite and etc.
6+
7+
## Example
8+
9+
Before transformation:
10+
11+
```javascript
12+
import { Button, List } from './components'
13+
```
14+
15+
After transformation:
16+
17+
```javascript
18+
import { Button } from './components/Button/Button'
19+
import { List } from './components/List/List'
20+
```
21+
22+
23+
## Installation
24+
25+
1. Install the package using npm:
26+
27+
```bash
28+
npm install --save-dev babel-plugin-transform-barrels
29+
```
30+
31+
2. Add the following to your webpack config file in the rule with a `babel-loader` loader:
32+
33+
```json
34+
"plugins": ["transform-barrels"]
35+
```
36+
37+
Alternatively, you can add `babel-plugin-transform-barrels` to your babelrc file:
38+
39+
```json
40+
"plugins": ["babel-plugin-transform-barrels"]
41+
```
42+
43+
## The Problem
44+
45+
There are two issues that can occur in bundle files created by Webpack when using barrel files:
46+
1. Unused CSS content in the CSS bundle file - this occurs when a CSS file is imported in a re-exported module of a barrel file.
47+
2. Unused Javascript code in Javascript bundle files when using dynamic imports - this occurs when a barrel file is imported inside two different dynamically imported modules. This barrel file and its re-exported modules will be included twice in the two bundle files.
48+
49+
### Note
50+
I recommend reading my article *Potential issues with barrel files in Webpack* for more information on possible issues can caused by barrel files.
51+
52+
## Possible Solutions
53+
54+
1. Use Babel plugins to convert import statements from indirect imports through barrel files to direct imports - this solution requires specific configuration for each package.
55+
2. Use Webpack's built-in solution of `sideEffects: ["*.css", "*.scss"]` - this solution should replace the first solution above. However, it causes a new issue where the order of imported modules is not based on the order of import statements, but on usage order. This can cause unexpected visual issues due to changes in the import order of CSS.
56+
57+
Both solutions above are not optimal, so I decided to develop my own plugin that does not require specific configuration for each package.
58+
59+
## My Plugin Solution
60+
My plugin examines every import in the Javascript project files and transforms it from an indirect import through a barrel file to a direct import from the module where the original export is declared.

package.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "babel-plugin-transform-barrels",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "src/index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"author": "",
10+
"license": "ISC",
11+
"devDependencies": {
12+
"@babel/parser": "^7.21.3",
13+
"@babel/types": "^7.21.3"
14+
}
15+
}

src/ast.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const fs = require("fs");
2+
const parser = require("@babel/parser");
3+
const t = require("@babel/types");
4+
5+
class AST {
6+
static filenameToAST = (filename) => {
7+
try {
8+
const content = fs.readFileSync(filename, "utf-8");
9+
return parser.parse(content, { sourceType: "module" });
10+
} catch (error) {
11+
return null;
12+
}
13+
};
14+
15+
static getSpecifierType(specifier) {
16+
if (specifier.local.name === "default")
17+
{
18+
return "default";
19+
} else return "named";
20+
}
21+
22+
static createASTImportDeclaration = ({name: specifierName, path: modulePath, type: specifierType}) => {
23+
return t.importDeclaration(
24+
[
25+
specifierType === "named"
26+
? t.importSpecifier(t.identifier(specifierName),t.identifier(specifierName))
27+
: t.importDefaultSpecifier(t.identifier(specifierName))
28+
,
29+
],
30+
t.stringLiteral(modulePath)
31+
)
32+
}
33+
}
34+
35+
module.exports = AST;

src/barrel.js

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
const t = require("@babel/types");
2+
const ospath = require("path");
3+
const fs = require("fs");
4+
const AST = require("./ast");
5+
6+
class PathFunctions {
7+
static isRelativePath(path) {
8+
return path.match(/^\.{0,2}\//);
9+
}
10+
11+
static isLocalModule(importModulePath) {
12+
try {
13+
return !!require.resolve(importModulePath) && !importModulePath.includes("node_modules");
14+
} catch {
15+
return false;
16+
}
17+
}
18+
19+
static isScriptFile(importModulePath) {
20+
return importModulePath.match(/\.(js|mjs|jsx|ts|tsx)$/);
21+
}
22+
23+
static getBaseUrlFromTsconfig() {
24+
try {
25+
const filename = ospath.resolve("jsconfig.json");
26+
const content = JSON.parse(fs.readFileSync(filename, "utf-8"));
27+
return content?.["compilerOptions"]?.["baseUrl"] || "./";
28+
} catch (error) {
29+
throw error;
30+
}
31+
}
32+
33+
static getModuleFile(filenameImportFrom, modulePath) {
34+
// solution for require function for ES modules
35+
// https://stackoverflow.com/questions/54977743/do-require-resolve-for-es-modules
36+
// https://stackoverflow.com/a/50053801
37+
// import { createRequire } from "module";
38+
// const require = createRequire(import.meta.url);
39+
try {
40+
const filenameDir = ospath.dirname(filenameImportFrom);
41+
const basePath = PathFunctions.isRelativePath(modulePath) ?
42+
filenameDir : ospath.resolve(PathFunctions.getBaseUrlFromTsconfig());
43+
return require.resolve(ospath.resolve(basePath, modulePath));
44+
} catch {
45+
try {
46+
return require.resolve(modulePath);
47+
} catch {
48+
return "MODULE_NOT_FOUND";
49+
}
50+
}
51+
}
52+
}
53+
54+
55+
class BarrelFilesMapping {
56+
constructor() {
57+
this.mapping = {};
58+
}
59+
60+
static isBarrelFile(modulePath) {
61+
return modulePath.endsWith("index.js");
62+
}
63+
64+
verifyFilePath (importModuleAbsolutePath) {
65+
return !BarrelFilesMapping.isBarrelFile(importModuleAbsolutePath) || !PathFunctions.isLocalModule(importModuleAbsolutePath) || !PathFunctions.isScriptFile(importModuleAbsolutePath)
66+
}
67+
68+
createSpecifiersMapping(fullPathModule) {
69+
const barrelAST = AST.filenameToAST(fullPathModule);
70+
this.mapping[fullPathModule] = {};
71+
barrelAST.program.body.forEach((node) => {
72+
if (t.isExportNamedDeclaration(node)) {
73+
const originalExportedPath = node.source?.value || fullPathModule;
74+
const absoluteExportedPath = node.source?.value ? PathFunctions.getModuleFile(fullPathModule, originalExportedPath) : fullPathModule;
75+
node.specifiers.forEach((specifier) => {
76+
const specifierName = specifier.exported.name;
77+
const specifierType = AST.getSpecifierType(specifier);
78+
this.mapping[fullPathModule][specifierName] =
79+
this.createDirectSpecifierObject(absoluteExportedPath, specifierName, specifierType);
80+
});
81+
if (t.isVariableDeclaration(node.declaration)) {
82+
const specifierType = "named";
83+
node.declaration.declarations.forEach((declaration) => {
84+
const specifierName = declaration.id.name;
85+
this.mapping[fullPathModule][specifierName] =
86+
this.createDirectSpecifierObject(absoluteExportedPath, specifierName, specifierType);
87+
});
88+
} else if (t.isFunctionDeclaration(node.declaration)) {
89+
const specifierType = "named";
90+
const specifierName = node.declaration.id.name;
91+
this.mapping[fullPathModule][specifierName] =
92+
this.createDirectSpecifierObject(absoluteExportedPath, specifierName, specifierType);
93+
}
94+
} else if (t.isExportAllDeclaration(node)) {
95+
const originalExportedPath = node.source.value;
96+
const absoluteExportedPath = PathFunctions.getModuleFile(fullPathModule, originalExportedPath);
97+
if (!this.mapping[absoluteExportedPath]) {
98+
this.createSpecifiersMapping(absoluteExportedPath);
99+
}
100+
Object.assign(this.mapping[fullPathModule],this.mapping[absoluteExportedPath]);
101+
}
102+
});
103+
}
104+
105+
createDirectSpecifierObject(fullPathModule, specifierName, specifierType) {
106+
if (BarrelFilesMapping.isBarrelFile(fullPathModule)) {
107+
if (!this.mapping[fullPathModule]) {
108+
this.createSpecifiersMapping(fullPathModule);
109+
}
110+
const originalPath = this.mapping[fullPathModule][specifierName]["path"];
111+
const originalName = this.mapping[fullPathModule][specifierName]["name"];
112+
const originalType = this.mapping[fullPathModule][specifierName]["type"];
113+
return this.createDirectSpecifierObject(originalPath, originalName, originalType);
114+
}
115+
return {
116+
name: specifierName,
117+
path: fullPathModule,
118+
type: specifierType,
119+
};
120+
}
121+
122+
getDirectSpecifierObject(fullPathModule, specifierName) {
123+
if (!this.mapping[fullPathModule]) {
124+
this.createSpecifiersMapping(fullPathModule);
125+
}
126+
return this.mapping[fullPathModule][specifierName];
127+
}
128+
}
129+
130+
const mapping = new BarrelFilesMapping();
131+
132+
const importDeclarationVisitor = (path, state) => {
133+
const parsedJSFile = state.filename
134+
const originalImportsPath = path.node.source.value;
135+
const originalImportsSpecifiers = path.node.specifiers;
136+
// const importModulePath = resolve.sync(originalImports.source.value,{basedir: ospath.dirname(state.filename)});
137+
const importModuleAbsolutePath = PathFunctions.getModuleFile(parsedJSFile, originalImportsPath);
138+
if (mapping.verifyFilePath(importModuleAbsolutePath)) return;
139+
const directSpecifierASTArray = originalImportsSpecifiers.map(
140+
(specifier) => {
141+
const directSpecifierObject = mapping.getDirectSpecifierObject(
142+
importModuleAbsolutePath,
143+
specifier.imported.name
144+
);
145+
return AST.createASTImportDeclaration(directSpecifierObject);
146+
}
147+
);
148+
path.replaceWithMultiple(directSpecifierASTArray);
149+
};
150+
151+
module.exports = function (babel) {
152+
return {
153+
visitor: {
154+
ImportDeclaration: importDeclarationVisitor,
155+
},
156+
};
157+
};

0 commit comments

Comments
 (0)