Skip to content

Commit

Permalink
add webpack alias support
Browse files Browse the repository at this point in the history
  • Loading branch information
FogelAI committed Nov 24, 2023
1 parent b96217a commit 83b4d06
Show file tree
Hide file tree
Showing 3 changed files with 165 additions and 108 deletions.
120 changes: 60 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
# babel-plugin-transform-barrels
This Babel plugin transforms indirect imports through a barrel file (index.js) into direct imports.

### Note
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.

## Example

Before transformation:

```javascript
import { Button, List } from './components'
```

After transformation:

```javascript
import { Button } from './components/Button/Button'
import { List } from './components/List/List'
```


## Installation

1. Install the package using npm:

```bash
npm install --save-dev babel-plugin-transform-barrels
```

2. Add the following to your webpack config file in the rule with a `babel-loader` loader:

```json
"plugins": ["transform-barrels"]
```

Alternatively, you can add `babel-plugin-transform-barrels` to your babelrc file:

```json
"plugins": ["babel-plugin-transform-barrels"]
```

## The Problem

There are two issues that can occur in bundle files created by Webpack when using barrel files:
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.
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.

### Note
I recommend reading my article *Potential issues with barrel files in Webpack* for more information on possible issues can caused by barrel files.

## Possible Solutions

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.
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.
Both solutions above are not optimal, so I decided to develop my own plugin that does not require specific configuration for each package.
## My Plugin Solution
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.
# babel-plugin-transform-barrels
This Babel plugin transforms indirect imports through a barrel file (index.js) into direct imports.

### Note
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.

## Example

Before transformation:

```javascript
import { Button, List } from './components'
```

After transformation:

```javascript
import { Button } from './components/Button/Button'
import { List } from './components/List/List'
```


## Installation

1. Install the package using npm:

```bash
npm install --save-dev babel-plugin-transform-barrels
```

2. Add the following to your webpack config file in the rule with a `babel-loader` loader:

```javascript
"plugins": ["transform-barrels", { webpackConfigFilename: __filename, ...(typeof module.exports === "function" && { args: arguments })}]
```
Alternatively, you can add `babel-plugin-transform-barrels` to your babelrc file:
```javascript
"plugins": ["babel-plugin-transform-barrels"]
```
## The Problem
There are two issues that can occur in bundle files created by Webpack when using barrel files:
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.
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.
### Note
I recommend reading my article [*Potential issues with barrel files in Webpack*](https://dev.to/fogel/potential-issues-with-barrel-files-in-webpack-4bf2) for more information on possible issues can caused by barrel files.
## Possible Solutions
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.
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.
Both solutions above are not optimal, so I decided to develop my own plugin that does not require specific configuration for each package.
## My Plugin Solution
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.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "babel-plugin-transform-barrels",
"version": "1.0.6",
"version": "1.0.7",
"description": "This Babel plugin transforms indirect imports through a barrel file (index.js) into direct imports.",
"homepage": "https://github.com/FogelAI/babel-plugin-transform-barrels",
"main": "src/barrel.js",
Expand Down
151 changes: 104 additions & 47 deletions src/barrel.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,60 +4,110 @@ const fs = require("fs");
const AST = require("./ast");

class PathFunctions {
static isObjectEmpty(obj) {
if (typeof obj === 'object' && Object.keys(obj).length !== 0) {
return false;
} else {
return true;
}
}

static isRelativePath(path) {
return path.match(/^\.{0,2}\//);
}

static isLocalModule(importModulePath) {
try {
return !!require.resolve(importModulePath) && !importModulePath.includes("node_modules");
} catch {
return false;
static checkIfModule(path) {
const notModuleRegExp = /^\.$|^\.[\\\/]|^\.\.$|^\.\.[\/\\]|^\/|^[A-Z]:[\\\/]/i;
const isModuleVar = !notModuleRegExp.test(path) || path.includes("node_modules");
return isModuleVar;
}

static getModuleAbsolutePath(parsedJSFile, convertedImportsPath) {
// solution for require function for ES modules
// https://stackoverflow.com/questions/54977743/do-require-resolve-for-es-modules
// https://stackoverflow.com/a/50053801
// import { createRequire } from "module";
// const require = createRequire(import.meta.url);
let absolutePath = convertedImportsPath;
if (!ospath.isAbsolute(convertedImportsPath)) {
absolutePath = ospath.join(ospath.dirname(parsedJSFile), convertedImportsPath);
}
const resolvedAbsolutePath = require.resolve(absolutePath);
return resolvedAbsolutePath;
}

static isScriptFile(importModulePath) {
return importModulePath.match(/\.(js|mjs|jsx|ts|tsx)$/);
}

class WebpackConfig {
constructor() {
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);

static getBaseUrlFromJTsconfig() {
try {
let content;
const jsconfig = ospath.resolve("jsconfig.json");
const tsconfig = ospath.resolve("tsconfig.json");
if (fs.existsSync(jsconfig)) {
content = JSON.parse(fs.readFileSync(jsconfig, "utf-8"));
} else if (fs.existsSync(tsconfig)) {
content = JSON.parse(fs.readFileSync(tsconfig, "utf-8"));
let alias = {};
if (typeof webpackConfigObj === 'object') {
if (!PathFunctions.isObjectEmpty(webpackConfigObj?.resolve?.alias)) {
alias = webpackConfigObj.resolve.alias;
}
return content?.["compilerOptions"]?.["baseUrl"] || "./";
} catch (error) {
throw error;
} else if (typeof webpackConfigObj === 'function') {
const args = plugin.options.args || [];
alias = webpackConfigObj(...args).resolve.alias;
}
}
this.aliasObj = alias;
return alias;
}

convertAliasToOriginal(parsedJSFile, originalImportsPath) {
let convertedPath = originalImportsPath;
const aliasObj = this.aliasObj;
const aliases = Object.keys(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(alias, 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}`;
}

static getModuleFile(filenameImportFrom, modulePath) {
// solution for require function for ES modules
// https://stackoverflow.com/questions/54977743/do-require-resolve-for-es-modules
// https://stackoverflow.com/a/50053801
// import { createRequire } from "module";
// const require = createRequire(import.meta.url);
try {
const filenameDir = ospath.dirname(filenameImportFrom);
const basePath = PathFunctions.isRelativePath(modulePath) ?
filenameDir : ospath.resolve(PathFunctions.getBaseUrlFromJTsconfig());
return require.resolve(ospath.resolve(basePath, modulePath));
} catch {
try {
return require.resolve(modulePath);
} catch {
return "MODULE_NOT_FOUND";
convertedPath = requiredFilePath;
break;
}
}
return convertedPath;
}
}


class BarrelFilesMapping {
constructor() {
this.mapping = {};
Expand All @@ -67,17 +117,14 @@ class BarrelFilesMapping {
return modulePath.endsWith("index.js");
}

verifyFilePath (importModuleAbsolutePath) {
return !BarrelFilesMapping.isBarrelFile(importModuleAbsolutePath) || !PathFunctions.isLocalModule(importModuleAbsolutePath) || !PathFunctions.isScriptFile(importModuleAbsolutePath)
}

createSpecifiersMapping(fullPathModule) {
const barrelAST = AST.filenameToAST(fullPathModule);
this.mapping[fullPathModule] = {};
barrelAST.program.body.forEach((node) => {
if (t.isExportNamedDeclaration(node)) {
const originalExportedPath = node.source?.value || fullPathModule;
const absoluteExportedPath = node.source?.value ? PathFunctions.getModuleFile(fullPathModule, originalExportedPath) : fullPathModule;
const convertedExportedPath = webpackConfig.convertAliasToOriginal(fullPathModule, originalExportedPath);
const absoluteExportedPath = PathFunctions.getModuleAbsolutePath(fullPathModule, convertedExportedPath);
node.specifiers.forEach((specifier) => {
const specifierExportedName = specifier.exported.name;
const specifierLocalName = specifier?.local?.name;
Expand All @@ -100,7 +147,8 @@ class BarrelFilesMapping {
}
} else if (t.isExportAllDeclaration(node)) {
const originalExportedPath = node.source.value;
const absoluteExportedPath = PathFunctions.getModuleFile(fullPathModule, originalExportedPath);
const convertedExportedPath = webpackConfig.convertAliasToOriginal(fullPathModule, originalExportedPath);
const absoluteExportedPath = PathFunctions.getModuleAbsolutePath(fullPathModule, convertedExportedPath);
if (!this.mapping[absoluteExportedPath]) {
this.createSpecifiersMapping(absoluteExportedPath);
}
Expand Down Expand Up @@ -137,14 +185,16 @@ class BarrelFilesMapping {
}

const mapping = new BarrelFilesMapping();
const webpackConfig = new WebpackConfig();

const importDeclarationVisitor = (path, state) => {
const parsedJSFile = state.filename
const originalImportsPath = path.node.source.value;
const originalImportsSpecifiers = path.node.specifiers;
// const importModulePath = resolve.sync(originalImports.source.value,{basedir: ospath.dirname(state.filename)});
const importModuleAbsolutePath = PathFunctions.getModuleFile(parsedJSFile, originalImportsPath);
if (mapping.verifyFilePath(importModuleAbsolutePath)) return;
const convertedImportsPath = webpackConfig.convertAliasToOriginal(parsedJSFile, originalImportsPath);
if (PathFunctions.checkIfModule(convertedImportsPath)) return;
const importModuleAbsolutePath = PathFunctions.getModuleAbsolutePath(parsedJSFile, convertedImportsPath);
if (!BarrelFilesMapping.isBarrelFile(importModuleAbsolutePath)) return;
const directSpecifierASTArray = originalImportsSpecifiers.map(
(specifier) => {
const directSpecifierObject = mapping.getDirectSpecifierObject(
Expand All @@ -164,7 +214,14 @@ const importDeclarationVisitor = (path, state) => {
};

module.exports = function (babel) {
const PLUGIN_KEY = 'transform-barrels';
return {
name: PLUGIN_KEY,
pre(state) {
const plugins = state.opts.plugins;
const plugin = plugins.find(plugin => plugin.key === PLUGIN_KEY);
webpackConfig.getWebpackAlias(plugin);
},
visitor: {
ImportDeclaration: importDeclarationVisitor,
},
Expand Down

0 comments on commit 83b4d06

Please sign in to comment.