├── .babelrc ├── .editorconfig ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src └── index.js └── test ├── error └── actual.js ├── feature ├── actual.js └── expect.js └── index.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "add-module-exports" 4 | ], 5 | "presets": [ 6 | ["@babel/env", { 7 | "loose": true, 8 | "targets": { 9 | "node": 4 10 | } 11 | }] 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain 2 | # consistent coding styles between different editors and IDEs. 3 | 4 | root = true 5 | 6 | [*] 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.log 3 | node_modules 4 | lib 5 | *.orig 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | sudo: false 3 | node_js: 4 | - 12 5 | - 10 6 | cache: 7 | directories: 8 | - ~/.npm 9 | git: 10 | depth: 10 11 | branches: 12 | only: 13 | - master 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 2.0.0 / 2021-03-21 2 | 3 | ### feat 4 | 5 | * feat: support recharts 2.x 6 | ## 1.2.0 / 2018-10-04 7 | 8 | ### feat 9 | 10 | * feat: support babel 7 11 | 12 | ## 1.1.0 / 2016-11-29 13 | 14 | * feat: commit 15 | 16 | ## 1.0.2 / 2016-05-19 17 | 18 | ### fix 19 | 20 | - add lib 21 | 22 | ## 1.0.1 / 2016-05-18 23 | 24 | ### fix 25 | 26 | - add test code 27 | 28 | ## 1.0.0 / 2016-05-18 29 | 30 | - Init the project 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 recharts 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # babel-plugin-recharts 2 | 3 | ## **Note:** This project is currently unmaintained and does not work with recharts 2.0 and above 4 | 5 | A babel plugin help you import less Recharts modules. 6 | 7 | [![npm version](https://badge.fury.io/js/babel-plugin-recharts.png)](https://badge.fury.io/js/babel-plugin-recharts) 8 | [![build status](https://travis-ci.org/recharts/babel-plugin-recharts.svg)](https://travis-ci.org/recharts/babel-plugin-recharts) 9 | [![npm downloads](https://img.shields.io/npm/dt/babel-plugin-recharts.svg?style=flat-square)](https://www.npmjs.com/package/babel-plugin-recharts) 10 | 11 | ## install 12 | 13 | ```sh 14 | $ npm i -D babel-plugin-recharts 15 | ``` 16 | 17 | ## Example 18 | 19 | The plugin automatically compiles `recharts` import, like this: 20 | 21 | ```jsx 22 | import { Line, Area, Pie, Treemap, Cell } from 'recharts'; 23 | ``` 24 | 25 | babel plugin will be parsed into: 26 | 27 | ```js 28 | "use strict"; 29 | 30 | require("recharts/lib/polyfill.js"); 31 | 32 | var _Line = _interopRequireDefault(require("recharts/lib/cartesian/Line.js")); 33 | 34 | var _Area = _interopRequireDefault(require("recharts/lib/cartesian/Area.js")); 35 | 36 | var _Treemap = _interopRequireDefault(require("recharts/lib/chart/Treemap.js")); 37 | 38 | var _Pie = _interopRequireDefault(require("recharts/lib/polar/Pie.js")); 39 | 40 | var _Cell = _interopRequireDefault(require("recharts/lib/component/Cell.js")); 41 | 42 | var _recharts = _interopRequireDefault(require("recharts")); 43 | 44 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 45 | ``` 46 | 47 | Hence you end up loading less modules. 48 | 49 | ## Usage 50 | 51 | You can choose to *either* edit your custom Babel configuration *or* your Webpack configuration. [Both options work.](https://github.com/recharts/babel-plugin-recharts/issues/7). 52 | 53 | ### .babelrc 54 | 55 | ```js 56 | { 57 | "plugins": ["recharts"] 58 | ... 59 | } 60 | ``` 61 | 62 | ### webpack.config.js 63 | 64 | ```js 65 | 'module': { 66 | 'loaders': [{ 67 | 'loader': 'babel-loader', 68 | 'test': /\.js$/, 69 | 'exclude': /node_modules/, 70 | 'query': { 71 | 'plugins': ['recharts'], 72 | ... 73 | } 74 | }] 75 | } 76 | ``` 77 | 78 | ## Limitations 79 | 80 | * You must use ES2015 imports to load recharts 81 | 82 | ## License 83 | 84 | [MIT](http://opensource.org/licenses/MIT) 85 | 86 | Copyright (c) 2015-2021 Recharts Group 87 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "babel-plugin-recharts", 3 | "version": "2.0.0", 4 | "description": "Modular Recharts builds without the hassle.", 5 | "main": "lib/index.js", 6 | "scripts": { 7 | "build": "rm -rf lib && babel src --out-dir lib", 8 | "dev": "rm -rf lib && babel src --out-dir lib -w", 9 | "test": "mocha --check-leaks --require @babel/register" 10 | }, 11 | "keywords": [ 12 | "babel-plugin", 13 | "recharts", 14 | "modules" 15 | ], 16 | "author": "recharts group", 17 | "license": "MIT", 18 | "devDependencies": { 19 | "@babel/cli": "^7.13.10", 20 | "@babel/core": "^7.13.10", 21 | "@babel/preset-env": "^7.13.10", 22 | "@babel/preset-stage-0": "^7.8.3", 23 | "@babel/register": "^7.13.8", 24 | "babel-plugin-add-module-exports": "^1.0.4", 25 | "mocha": "^8.3.2", 26 | "recharts": "^2.0.8" 27 | }, 28 | "files": [ 29 | "lib", 30 | "*.md" 31 | ], 32 | "dependencies": { 33 | "@babel/parser": "^7.13.10", 34 | "@babel/traverse": "^7.13.0", 35 | "@babel/types": "^7.13.0" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * restraint: 3 | * 1. common code: import 'xx'; 4 | * 2. export: export xx from xx, export x, { xx } from 'xx'; 5 | * 6 | */ 7 | 8 | import Module from 'module'; 9 | import path from 'path'; 10 | import fs from 'fs'; 11 | import * as babelParser from '@babel/parser'; 12 | import traverse from '@babel/traverse'; 13 | import * as t from '@babel/types'; 14 | 15 | const recharts = 'recharts'; 16 | const rechartsLib = 'recharts/lib'; 17 | 18 | const _module = new Module(); 19 | 20 | const rechartsLibPath = path.dirname(Module._resolveFilename('recharts', { 21 | ..._module, 22 | paths: Module._nodeModulePaths(process.cwd()), 23 | })); 24 | const rechartsPath = path.join(rechartsLibPath, '..'); 25 | const rechartsSrcPath = path.join(rechartsPath, 'src'); 26 | const rechartsSrcIndexPath = path.join(rechartsSrcPath, 'index.ts'); 27 | const srcCode = fs.readFileSync(rechartsSrcIndexPath, 'utf-8'); 28 | 29 | const srcAst = babelParser.parse(srcCode, { 30 | sourceType: 'module', 31 | plugins: ['exportExtensions', 'typescript'], 32 | }); 33 | 34 | function findPath(source) { 35 | const finalModule = { 36 | ..._module, 37 | paths: Module._nodeModulePaths(rechartsSrcPath), 38 | }; 39 | 40 | const nodeMajorVersion = process.versions.node.split('.')[0]; 41 | let paths; 42 | let id; 43 | // This internal API has changed it's functionality 44 | if (nodeMajorVersion < 12) { 45 | // Node.js version < 12: use _resolveLookupPaths 46 | [id, paths] = Module._resolveLookupPaths(source, finalModule); 47 | } else { 48 | // Node.js version >= 12: use _nodeModulePaths from above 49 | paths = finalModule.paths; 50 | } 51 | const finalPaths = [...paths, rechartsSrcPath]; 52 | 53 | let sourceFullPath; 54 | try { 55 | // All components use the `*.tsx` file extension 56 | const fullTSXPath = path.resolve(rechartsSrcPath, source.indexOf('.tsx') >= 0 ? source : `${source}.tsx`); 57 | require.resolve(fullTSXPath); 58 | sourceFullPath = fullTSXPath; 59 | } catch(err) { 60 | 61 | } 62 | try { 63 | // Files under `utils` use the `*.ts` file extension 64 | const fulllTSPath = path.resolve(rechartsSrcPath, source.indexOf('.ts') >= 0 ? source : `${source}.ts`); 65 | require.resolve(fulllTSPath); 66 | sourceFullPath = fulllTSPath; 67 | } catch(err) { 68 | 69 | } 70 | if (sourceFullPath) { 71 | // parse the component of project src 72 | // full quote path 73 | const sourceLibPath = `${rechartsLib}/${path.relative(rechartsSrcPath, sourceFullPath)}`; 74 | return sourceLibPath.replace('.tsx', '.js').replace('.ts', '.js'); 75 | } 76 | 77 | const absPath = Module._findPath(source, finalPaths); 78 | 79 | if (absPath && (absPath.indexOf(path.join(rechartsPath, 'node_modules')) >= 0) || absPath.indexOf('node_modules') >= 0) { 80 | // node_modules source 81 | return source; 82 | } 83 | 84 | return ''; 85 | } 86 | 87 | let pkgMap = {}; 88 | let commonImport = []; 89 | 90 | traverse(srcAst, { 91 | ImportDeclaration(path) { 92 | const { source, specifiers } = path.node; 93 | 94 | if (!specifiers.length) { 95 | // get common import like import 'polyfill' 96 | commonImport = [...commonImport, source.value]; 97 | } 98 | }, 99 | 100 | ExportNamedDeclaration(path) { 101 | const { source, specifiers } = path.node; 102 | 103 | specifiers.forEach(spec => { 104 | const { exported, local } = spec; 105 | 106 | if (t.isExportDefaultSpecifier(spec)) { 107 | pkgMap = { 108 | ...pkgMap, 109 | [exported.name]: source.value, 110 | }; 111 | } else { 112 | pkgMap = { 113 | ...pkgMap, 114 | [exported.name]: [source.value, local.name], 115 | }; 116 | } 117 | }); 118 | }, 119 | }); 120 | 121 | Object.keys(pkgMap).forEach(key => { 122 | const pkgMapVal = pkgMap[key]; 123 | pkgMap[key] = findPath(Array.isArray(pkgMapVal) ? pkgMapVal[0] : pkgMapVal); 124 | }); 125 | 126 | commonImport = commonImport.map(source => { 127 | return findPath(source); 128 | }); 129 | 130 | export default function ({types: t}) { 131 | // import common code once in a file 132 | let hasAddCommonCode = false; 133 | 134 | return { 135 | visitor: { 136 | ImportDeclaration(path) { 137 | const { node } = path; 138 | const { specifiers, source } = node; 139 | const { value: pkgId } = source; 140 | const specs = []; 141 | 142 | if (pkgId !== recharts) { 143 | return ; 144 | } 145 | 146 | if (!specifiers.filter(t.isImportSpecifier).length) { 147 | return; 148 | } 149 | 150 | specifiers.forEach(spec => { 151 | const { local , imported } = spec; 152 | const { name: localName } = local; 153 | 154 | let importedPath = recharts; 155 | 156 | if (t.isImportSpecifier(spec)) { 157 | const { name: importedName } = imported; 158 | 159 | spec = t.importDefaultSpecifier(t.identifier(localName)); 160 | 161 | if (!pkgMap[importedName]) { 162 | throw new Error(`Recharts ${importedName} was not in known modules.`); 163 | } 164 | 165 | importedPath = pkgMap[importedName]; 166 | } 167 | 168 | if (!hasAddCommonCode) { 169 | hasAddCommonCode = true; 170 | commonImport.forEach(cPath => { 171 | path.insertBefore(t.importDeclaration([], t.stringLiteral(cPath))); 172 | }); 173 | } 174 | 175 | path.insertAfter(t.importDeclaration([spec], t.stringLiteral(importedPath))); 176 | }); 177 | 178 | path.remove(); 179 | } 180 | } 181 | }; 182 | } 183 | -------------------------------------------------------------------------------- /test/error/actual.js: -------------------------------------------------------------------------------- 1 | import { xxx } from 'recharts'; 2 | -------------------------------------------------------------------------------- /test/feature/actual.js: -------------------------------------------------------------------------------- 1 | import { Line as RechartsLine } from 'recharts'; 2 | import { Area } from 'recharts'; 3 | import { Pie, Treemap } from 'recharts'; 4 | import recharts, { Cell } from 'recharts'; 5 | 6 | -------------------------------------------------------------------------------- /test/feature/expect.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _Line = _interopRequireDefault(require("recharts/lib/cartesian/Line.js")); 4 | 5 | var _Area = _interopRequireDefault(require("recharts/lib/cartesian/Area.js")); 6 | 7 | var _Treemap = _interopRequireDefault(require("recharts/lib/chart/Treemap.js")); 8 | 9 | var _Pie = _interopRequireDefault(require("recharts/lib/polar/Pie.js")); 10 | 11 | var _Cell = _interopRequireDefault(require("recharts/lib/component/Cell.js")); 12 | 13 | var _recharts = _interopRequireDefault(require("recharts")); 14 | 15 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 16 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | import assert from 'assert'; 2 | import path from 'path'; 3 | import fs from 'fs'; 4 | import plugin from '../src/index'; 5 | import { transformFileSync } from '@babel/core'; 6 | 7 | describe('cherry-picked modular builds', () => { 8 | it('should work with cherry-pick modular builds', () => { 9 | const actualPath = path.join(__dirname, 'feature/actual.js'); 10 | const expectedPath = path.join(__dirname, 'feature/expect.js'); 11 | 12 | const actual = transformFileSync(actualPath, { 13 | 'plugins': [plugin], 14 | }).code; 15 | const expected = fs.readFileSync(expectedPath, 'utf8'); 16 | 17 | assert.strictEqual(actual.trim(), expected.trim()); 18 | }); 19 | 20 | it('should throw an error', () => { 21 | const errorPath = path.join(__dirname, 'error/actual.js'); 22 | 23 | assert.throws(function() { 24 | transformFileSync(errorPath, { 25 | 'plugins': [plugin], 26 | }).code; 27 | }); 28 | }); 29 | }); 30 | --------------------------------------------------------------------------------