diff --git a/README.md b/README.md index 088be6a..7d189a5 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/package.json b/package.json index 2ba5599..1b00ceb 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/barrel.js b/src/barrel.js index ffde64d..210e66f 100644 --- a/src/barrel.js +++ b/src/barrel.js @@ -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 = {}; @@ -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; @@ -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); } @@ -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( @@ -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, },