├── .eslintrc.js ├── .github └── workflows │ └── node.js.yml ├── .gitignore ├── .husky ├── .gitignore └── prepare-commit-msg ├── CHANGELOG.md ├── LICENSE ├── README.md ├── bin └── esr.js ├── jest.js ├── package.json ├── pnpm-lock.yaml ├── prettier.config.js ├── register.js ├── renovate.json ├── src ├── cache.ts ├── cli.ts ├── esbuild.ts ├── hook.ts ├── index.ts ├── jest.ts └── register.ts └── tsconfig.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: [ 3 | "eslint:recommended", 4 | "plugin:@typescript-eslint/recommended", 5 | "plugin:@typescript-eslint/recommended-requiring-type-checking", 6 | "prettier", 7 | "plugin:eslint-comments/recommended", 8 | "plugin:node/recommended", 9 | "plugin:jest/recommended", 10 | "plugin:jest/style", 11 | "plugin:import/errors", 12 | "plugin:import/warnings", 13 | "plugin:import/typescript", 14 | "plugin:unicorn/recommended", 15 | "plugin:promise/recommended", 16 | ], 17 | plugins: ["@typescript-eslint", "prettier", "jest", "import", "promise"], 18 | root: true, 19 | reportUnusedDisableDirectives: true, 20 | env: { node: true }, 21 | settings: { node: { tryExtensions: [".js", ".ts", ".vue"] } }, 22 | ignorePatterns: ["node_modules/", "build/", "dist/"], 23 | parserOptions: { 24 | parser: "@typescript-eslint/parser", 25 | ecmaVersion: 2020, 26 | sourceType: "module", 27 | ecmaFeatures: { jsx: true }, 28 | createDefaultProgram: true, 29 | project: "./tsconfig.json", 30 | impliedStrict: true, 31 | warnOnUnsupportedTypeScriptVersion: false, 32 | }, 33 | overrides: [ 34 | { 35 | files: [ 36 | "**/__tests__/*.{j,t}s?(x)", 37 | "**/tests/unit/**/*.spec.{j,t}s?(x)", 38 | ], 39 | env: { jest: true }, 40 | }, 41 | ], 42 | rules: { 43 | "import/default": "off", 44 | "import/no-namespace": "error", 45 | "no-console": "error", 46 | "no-debugger": "off", 47 | "eslint-comments/disable-enable-pair": ["error", { allowWholeFile: true }], 48 | "node/no-unsupported-features/es-syntax": [ 49 | "error", 50 | { version: ">=15.3.0", ignores: ["modules", "dynamicImport"] }, 51 | ], 52 | "node/no-unsupported-features/node-builtins": [ 53 | "error", 54 | { version: ">=15.3.0", ignores: [] }, 55 | ], 56 | "node/no-unsupported-features/es-builtins": [ 57 | "error", 58 | { version: ">=15.3.0", ignores: [] }, 59 | ], 60 | "node/no-missing-import": [ 61 | "error", 62 | { tryExtensions: [".js", ".ts", ".d.ts"] }, 63 | ], 64 | "array-callback-return": "error", 65 | "prefer-template": "warn", 66 | "prefer-promise-reject-errors": "error", 67 | "require-unicode-regexp": "error", 68 | yoda: "error", 69 | "prefer-spread": "error", 70 | "unicorn/filename-case": "off", 71 | "unicorn/prefer-node-protocol": "off", 72 | "unicorn/no-object-as-default-parameter": "off", 73 | "unicorn/no-reduce": "off", 74 | "unicorn/no-process-exit": "off", 75 | "lines-between-class-members": [ 76 | "error", 77 | "always", 78 | { exceptAfterSingleLine: true }, 79 | ], 80 | // "promise/valid-params": "off", 81 | "prettier/prettier": "warn", 82 | "unicorn/prevent-abbreviations": "off", 83 | "unicorn/no-null": "off", 84 | "unicorn/explicit-length-check": "off", 85 | "unicorn/consistent-function-scoping": "off", 86 | "no-restricted-imports": [ 87 | "error", 88 | { 89 | paths: [ 90 | { 91 | name: "type-graphql", 92 | importNames: ["Arg", "Args", "Resolver", "Query"], 93 | message: "Please use the imports from '@nestjs/graphql' instead.", 94 | }, 95 | { 96 | name: "lodash", 97 | importNames: ["default"], 98 | message: 99 | "Please use the seperate imports '@lodash/debounce' instead.", 100 | }, 101 | ], 102 | }, 103 | ], 104 | "@typescript-eslint/explicit-function-return-type": "off", 105 | "@typescript-eslint/explicit-module-boundary-types": "off", 106 | "@typescript-eslint/restrict-template-expressions": "off", 107 | "@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }], 108 | "jest/expect-expect": [ 109 | "warn", 110 | { assertFunctionNames: ["expect", "request.get.expect"] }, 111 | ], 112 | }, 113 | } 114 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [main] 9 | pull_request: 10 | branches: [main] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | strategy: 17 | matrix: 18 | node-version: [16.x] 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | - name: Use Node.js ${{ matrix.node-version }} 23 | uses: actions/setup-node@v3 24 | with: 25 | node-version: ${{ matrix.node-version }} 26 | - run: npm install -g pnpm 27 | - run: pnpm install 28 | - run: pnpm run build 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .eslintcache 3 | .ultra.cache.json 4 | lib 5 | tt.* -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/prepare-commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx devmoji -e --lint 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### [2.2.1](https://github.com/folke/esbuild-runner/compare/2.2.0...2.2.1) (2021-08-30) 2 | 3 | ## [2.2.0](https://github.com/folke/esbuild-runner/compare/2.1.0...2.2.0) (2021-06-04) 4 | 5 | 6 | ### Features 7 | 8 | * ✨ added support for custom loaders [#24](https://github.com/folke/esbuild-runner/issues/24) ([ad3268e](https://github.com/folke/esbuild-runner/commit/ad3268e1936a350271bfd8706f473f0a8baf1be9)) 9 | 10 | ## [2.1.0](https://github.com/folke/esbuild-runner/compare/2.0.0...2.1.0) (2021-06-01) 11 | 12 | 13 | ### Features 14 | 15 | * ✨ allow overriding esbuild.external [#23](https://github.com/folke/esbuild-runner/issues/23) ([801eb20](https://github.com/folke/esbuild-runner/commit/801eb2015f2ba1f4aa4df06ec02308f6b7fab392)) 16 | 17 | ## [2.0.0](https://github.com/folke/esbuild-runner/compare/1.4.0...2.0.0) (2021-05-29) 18 | 19 | 20 | ### ⚠ BREAKING CHANGES 21 | 22 | * 💥 ♻️ renamed the config file from esbuild.config.js -> esbuild-runner.config.js 23 | 24 | ### Code Refactoring 25 | 26 | * 💥 ♻️ renamed the config file from esbuild.config.js -> esbuild-runner.config.js ([728518d](https://github.com/folke/esbuild-runner/commit/728518d384389ae59dffb42fb1a41e48cabb12d6)) 27 | 28 | ## [1.4.0](https://github.com/folke/esbuild-runner/compare/1.3.2...1.4.0) (2021-05-26) 29 | 30 | 31 | ### Features 32 | 33 | * ✨ added config for passing build / transform options to the api [#14](https://github.com/folke/esbuild-runner/issues/14) ([200447e](https://github.com/folke/esbuild-runner/commit/200447e143d59cb263e2a7e51c10666fd1b05feb)) 34 | * ✨ esbuild.config.js [#14](https://github.com/folke/esbuild-runner/issues/14) [#19](https://github.com/folke/esbuild-runner/issues/19) ([9dfb19f](https://github.com/folke/esbuild-runner/commit/9dfb19f8fdead4d56abe4b70fe16bde745fd4d9c)) 35 | 36 | 37 | ### Bug Fixes 38 | 39 | * 🐛 added esbuild as a peer dependency. Fixes [#16](https://github.com/folke/esbuild-runner/issues/16) ([8656874](https://github.com/folke/esbuild-runner/commit/865687436b3a43c5c175d9c852cfc096c45e2735)) 40 | 41 | ### [1.3.2](https://github.com/folke/esbuild-runner/compare/1.3.1...1.3.2) (2020-12-14) 42 | 43 | 44 | ### Bug Fixes 45 | 46 | * 🐛 use rmdirSync instead of rmSync for compatibility with older nodejs versions ([a57482a](https://github.com/folke/esbuild-runner/commit/a57482a86345be3adb1f1598828de82261ce08a6)) 47 | 48 | ### [1.3.1](https://github.com/folke/esbuild-runner/compare/1.3.0...1.3.1) (2020-12-09) 49 | 50 | 51 | ### Bug Fixes 52 | 53 | * 🐛 show message and exit, after clearing cache ([91aafc0](https://github.com/folke/esbuild-runner/commit/91aafc00b552a7f665f1bce25363c412cf153f92)) 54 | 55 | ## [1.3.0](https://github.com/folke/esbuild-runner/compare/1.2.0...1.3.0) (2020-12-09) 56 | 57 | 58 | ### Features 59 | 60 | * ✨ added esbuild transform --cache ([4ca2415](https://github.com/folke/esbuild-runner/commit/4ca241533d52b7a94388293ad26087f6bbfa0c32)) 61 | * ✨ added option to use transform with caching instead of bundling to the API ([9345b78](https://github.com/folke/esbuild-runner/commit/9345b7838a9733c6b567aefe34aabf6500597674)) 62 | * ✨ enable support for nextjs by transpiling .js files ([5bcc8be](https://github.com/folke/esbuild-runner/commit/5bcc8bef1213f078550701d2c874bc4f37ba7b94)) 63 | 64 | ## [1.2.0](https://github.com/folke/esbuild-runner/compare/1.1.1...1.2.0) (2020-12-09) 65 | 66 | 67 | ### Features 68 | 69 | * ✨ added support for source maps ([3435f7e](https://github.com/folke/esbuild-runner/commit/3435f7ea02102da8612ba95d9590f0772d58db4d)) 70 | 71 | ### [1.1.1](https://github.com/folke/esbuild-runner/compare/1.1.0...1.1.1) (2020-12-07) 72 | 73 | 74 | ### Bug Fixes 75 | 76 | * 🐛 renamed esn.js to esr.js ([4caeafd](https://github.com/folke/esbuild-runner/commit/4caeafd768f0d88dfb1dda5d5ab5d9076ce7acde)) 77 | 78 | ## 1.1.0 (2020-12-07) 79 | 80 | 81 | ### Features 82 | 83 | * ✨ added Jest transform module ([6122523](https://github.com/folke/esbuild-runner/commit/61225232f2c7371afb1dd5aefd38229f14ec2e3a)) 84 | * ✨ allow `node -r es-node/register` to automatically transpile source code ([7a05c58](https://github.com/folke/esbuild-runner/commit/7a05c58c033537a8da5c1b00464ea3f6adb50870)) 85 | * ✨ initial version 🎉 ([4669746](https://github.com/folke/esbuild-runner/commit/466974606b4b727f54f1fb12adb01573c6e13b16)) 86 | 87 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # :zap: Esbuild Runner (`esr`) 2 | 3 | Super-fast on-the-fly transpilation of modern JS, TypeScript and JSX using [esbuild](https://github.com/evanw/esbuild). 4 | 5 | **esr** makes it easy to run arbitrary code or tests without needing to **build** your whole project. It's a great way to improve your development workflow. 6 | 7 | ## ✨ Usage 8 | 9 | The easiest way to use **esbuild-runner** is to install it globally and use the included `esr` binary. 10 | 11 | ```shell 12 | $ esr hello-world.ts 13 | ``` 14 | 15 | Alternatively, you can _require_ **esbuild-runner** within any nodejs process to include realtime transpilation: 16 | 17 | ```shell 18 | $ node -r esbuild-runner/register hello-world.ts 19 | ``` 20 | 21 | In order to use **esbuild-runner** with Jest, you need to configure a [Jest transform](https://jestjs.io/docs/en/configuration.html#transform-objectstring-pathtotransformer--pathtotransformer-object) in your `jest.config.js` 22 | 23 | ```js 24 | module.exports = { 25 | transform: { 26 | "\\.ts$": "esbuild-runner/jest", 27 | }, 28 | } 29 | ``` 30 | 31 | VSCode Debugging 32 | 33 | ```JSON 34 | { 35 | "version": "0.2.0", 36 | "configurations": [ 37 | { 38 | "name": "Debug with esbuild-runner", 39 | "program": "${workspaceFolder}/hello-world.ts", 40 | "runtimeArgs": [ 41 | "-r", 42 | "esbuild-runner/register" 43 | ], 44 | "request": "launch", 45 | "sourceMaps": true, 46 | "skipFiles": [ 47 | "/**" 48 | ], 49 | "type": "pwa-node" 50 | } 51 | ] 52 | } 53 | ``` 54 | 55 | ## ⚙️ Configuration 56 | 57 | `esr` provides two different ways to transpile your code: 58 | 59 | - **bundling** _(default)_: this transpiles the script and all its dependencies in typically one invocation of **esbuild**. Dependencies defined in `package.json` or `node_modules` will never be transpiled. Running `esr` will **always** transpile the code. No caching is used. 60 | - **transform** _(`--cache`)_: this method will invoke **esbuild** for **every source file**, but will cache the result. This means that the initial run will be slower, but after that, only changed source files will be transpiled. 61 | 62 | ```shell 63 | $ bin/esr.js --help 64 | Usage: esr [options] [file-options] 65 | 66 | --cache Transform on a file per file basis and cache code 67 | --clearCache Clear transform cache 68 | --help|-h Display this help message 69 | 70 | ``` 71 | 72 | To customize the options passed to esbuild, you can create an `esbuild-runner.config.js` file in the current directory or one of the ancestor directories. 73 | 74 | ```js 75 | // example esbuild-runner.config.js 76 | module.exports = { 77 | type: "bundle", // bundle or transform (see description above) 78 | esbuild: { 79 | // Any esbuild build or transform options go here 80 | target: "esnext", 81 | }, 82 | } 83 | ``` 84 | 85 | ## 📦 Installation 86 | 87 | Simply install the **esbuild-runner** npm package using your favorite package manager. 88 | 89 | - globally ... 90 | 91 | ```shell 92 | $ npm install -g esbuild-runner 93 | ``` 94 | 95 | - ... or locally in your project 96 | 97 | ```shell 98 | $ npm add --dev esbuild-runner 99 | ``` 100 | 101 | ## 👋 Contributing 102 | 103 | Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. 104 | 105 | ## ⚖ License 106 | 107 | [Apache 2.0](https://github.com/folke/esbuild-runner/blob/main/LICENSE) 108 | 109 | 110 | -------------------------------------------------------------------------------- /bin/esr.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // eslint-disable-next-line @typescript-eslint/no-var-requires 3 | require("../lib/cli").main() 4 | -------------------------------------------------------------------------------- /jest.js: -------------------------------------------------------------------------------- 1 | module.exports = require("./lib/jest") 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "esbuild-runner", 3 | "version": "2.2.1", 4 | "description": "Super-fast on-the-fly transpilation of modern JS, TypeScript and JSX using esbuild", 5 | "repository": "http://github.com/folke/esbuild-runner", 6 | "main": "lib/index.js", 7 | "keywords": [ 8 | "esbuild", 9 | "typescript", 10 | "commonjs", 11 | "jest", 12 | "esnext", 13 | "cjs", 14 | "node", 15 | "nodejs", 16 | "es6", 17 | "esm", 18 | "ts-node" 19 | ], 20 | "bin": { 21 | "esr": "./bin/esr.js" 22 | }, 23 | "author": "Folke Lemaitre", 24 | "license": "Apache License 2.0", 25 | "scripts": { 26 | "clean": "rimraf lib", 27 | "lint": "eslint src --ext .ts,.js --cache", 28 | "prebuild": "npm run clean && npm run lint", 29 | "build:ts": "tsc --pretty", 30 | "build": "npm run build:ts", 31 | "run": "node ." 32 | }, 33 | "files": [ 34 | "lib", 35 | "bin", 36 | "jest.js", 37 | "register.js" 38 | ], 39 | "ultra": { 40 | "concurrent": [ 41 | "lint", 42 | "prebuild", 43 | "build", 44 | "ultra" 45 | ] 46 | }, 47 | "release-it": { 48 | "hooks": { 49 | "before:init": "ultra --color lint", 50 | "after:bump": "ultra --color build" 51 | }, 52 | "npm": { 53 | "publish": true 54 | }, 55 | "git": { 56 | "commitMessage": "chore(release): ${version}" 57 | }, 58 | "github": { 59 | "release": true 60 | }, 61 | "plugins": { 62 | "@release-it/conventional-changelog": { 63 | "preset": "conventionalcommits", 64 | "infile": "CHANGELOG.md" 65 | } 66 | } 67 | }, 68 | "devDependencies": { 69 | "@release-it/conventional-changelog": "5.1.1", 70 | "@types/eslint": "8.4.7", 71 | "@types/eslint-plugin-prettier": "3.1.0", 72 | "@types/node": "18.8.5", 73 | "@types/prettier": "2.7.1", 74 | "@types/rimraf": "3.0.2", 75 | "@types/source-map-support": "0.5.6", 76 | "@typescript-eslint/eslint-plugin": "5.40.1", 77 | "@typescript-eslint/parser": "5.40.1", 78 | "devmoji": "2.3.0", 79 | "esbuild": "0.15.12", 80 | "eslint": "8.25.0", 81 | "eslint-config-prettier": "8.5.0", 82 | "eslint-plugin-eslint-comments": "3.2.0", 83 | "eslint-plugin-import": "2.26.0", 84 | "eslint-plugin-jest": "27.1.3", 85 | "eslint-plugin-node": "11.1.0", 86 | "eslint-plugin-prettier": "4.2.1", 87 | "eslint-plugin-promise": "6.1.1", 88 | "eslint-plugin-unicorn": "44.0.2", 89 | "husky": "8.0.1", 90 | "jest": "29.2.1", 91 | "prettier": "2.7.1", 92 | "release-it": "15.5.0", 93 | "rimraf": "3.0.2", 94 | "type-fest": "3.1.0", 95 | "typescript": "4.8.4", 96 | "typesync": "0.9.2" 97 | }, 98 | "peerDependencies": { 99 | "esbuild": "*" 100 | }, 101 | "dependencies": { 102 | "source-map-support": "0.5.21", 103 | "tslib": "2.4.0" 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | semi: false, 3 | singleQuote: false, 4 | tabWidth: 2, 5 | useTabs: false, 6 | printWidth: 80, 7 | trailingComma: "es5", 8 | proseWrap: "preserve", 9 | } 10 | -------------------------------------------------------------------------------- /register.js: -------------------------------------------------------------------------------- 1 | module.exports = require("./lib/register") 2 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base", 4 | ":semanticCommits", 5 | "group:allApollographql", 6 | "group:definitelyTyped", 7 | "group:vueMonorepo", 8 | "group:nestMonorepo", 9 | "group:fortawesome", 10 | "group:linters", 11 | "group:test", 12 | "group:allNonMajor" 13 | ], 14 | "masterIssue": true, 15 | "prHourlyLimit": 20, 16 | "packageRules": [ 17 | { 18 | "updateTypes": ["patch", "pin", "digest"], 19 | "automerge": true 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /src/cache.ts: -------------------------------------------------------------------------------- 1 | import os from "os" 2 | import fs from "fs" 3 | import path from "path" 4 | import crypto from "crypto" 5 | 6 | const tmpPath = path.resolve(os.tmpdir(), "esbuild-runner-cache") 7 | if (!fs.existsSync(tmpPath)) fs.mkdirSync(tmpPath, { recursive: true }) 8 | 9 | function clear() { 10 | if (fs.existsSync(tmpPath)) { 11 | fs.rmdirSync(tmpPath, { recursive: true }) 12 | fs.mkdirSync(tmpPath, { recursive: true }) 13 | } 14 | } 15 | 16 | function get(filename: string, transpiler: () => string) { 17 | const hash = crypto 18 | .createHash("md5") 19 | .update(path.resolve(filename)) 20 | .update(process.version) 21 | .digest("hex") 22 | 23 | const compiledPath = path.resolve(tmpPath, `${hash}.js`) 24 | if ( 25 | !fs.existsSync(compiledPath) || 26 | fs.statSync(compiledPath).mtime < fs.statSync(filename).mtime 27 | ) { 28 | const code = transpiler() 29 | fs.writeFileSync(compiledPath, code, { encoding: "utf8" }) 30 | return code 31 | } 32 | return fs.readFileSync(compiledPath, { encoding: "utf8" }) 33 | } 34 | 35 | export default { get, clear, tmpPath } 36 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-process-exit */ 2 | import fs from "fs" 3 | import Module from "module" 4 | import path from "path" 5 | import cache from "./cache" 6 | import { install } from "./hook" 7 | 8 | function help() { 9 | // eslint-disable-next-line no-console 10 | console.log(`Usage: esr [options] [file-options] 11 | 12 | --cache Transform on a file per file basis and cache code 13 | --clearCache Clear transform cache 14 | --help|-h Display this help message 15 | `) 16 | process.exit(1) 17 | } 18 | 19 | function parseArgs(args: string[] = process.argv) { 20 | const nodePath = args[0] 21 | // Remove node path 22 | args.shift() 23 | // Remove esr path 24 | args.shift() 25 | 26 | const options = { debug: false, cache: false } 27 | 28 | for (let a = 0; a < args.length; a++) { 29 | const arg = args[a] 30 | switch (arg) { 31 | case "--help": 32 | case "-h": { 33 | help() 34 | continue 35 | } 36 | 37 | case "--clearCache": 38 | case "--clear-cache": { 39 | cache.clear() 40 | // eslint-disable-next-line no-console 41 | console.log(`Cleared ${cache.tmpPath}`) 42 | process.exit(0) 43 | continue 44 | } 45 | 46 | case "--cache": { 47 | options.cache = true 48 | continue 49 | } 50 | 51 | case "--debug": { 52 | options.debug = true 53 | continue 54 | } 55 | 56 | default: { 57 | args = args.slice(a) 58 | args.unshift(nodePath) 59 | return { options, args } 60 | } 61 | } 62 | } 63 | return { options, args: [nodePath] } 64 | } 65 | 66 | export function main() { 67 | const { options, args } = parseArgs() 68 | 69 | if (args.length >= 2 && fs.existsSync(args[1])) { 70 | process.argv = args 71 | process.argv[1] = path.resolve(process.argv[1]) 72 | install({ 73 | type: options.cache ? "transform" : "bundle", 74 | debug: options.debug, 75 | }) 76 | Module.runMain() 77 | } else { 78 | help() 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/esbuild.ts: -------------------------------------------------------------------------------- 1 | import { 2 | buildSync, 3 | Loader, 4 | transformSync, 5 | CommonOptions, 6 | TransformOptions, 7 | BuildOptions, 8 | } from "esbuild" 9 | import fs from "fs" 10 | import path from "path" 11 | // eslint-disable-next-line import/no-unresolved 12 | import { PackageJson } from "type-fest" 13 | import cache from "./cache" 14 | 15 | export type TranspileOptions = { 16 | type: "bundle" | "transform" 17 | debug: boolean 18 | esbuild?: CommonOptions & TransformOptions & BuildOptions 19 | } 20 | const defaultOptions: TranspileOptions = { type: "bundle", debug: false } 21 | 22 | const commonOptions: CommonOptions = { 23 | format: "cjs", 24 | logLevel: "error", 25 | target: [`node${process.version.slice(1)}`], 26 | minify: false, 27 | sourcemap: "inline", 28 | } 29 | 30 | const pkgPath = path.resolve(".", "package.json") 31 | let externals: string[] = [] 32 | if (fs.existsSync(pkgPath)) { 33 | const pkg = JSON.parse( 34 | fs.readFileSync(pkgPath, { encoding: "utf8" }) 35 | ) as PackageJson 36 | externals = [ 37 | ...Object.keys(pkg.dependencies ?? {}), 38 | ...Object.keys(pkg.devDependencies ?? {}), 39 | ] 40 | } 41 | 42 | export const loaders: Record = { 43 | ".js": "js", 44 | ".mjs": "js", 45 | ".cjs": "js", 46 | ".jsx": "jsx", 47 | ".ts": "ts", 48 | ".tsx": "tsx", 49 | // ".css": "css", 50 | ".json": "json", 51 | // ".txt": "text", 52 | } 53 | 54 | export function supports(filename: string) { 55 | if (filename.includes("node_modules")) return false 56 | return path.extname(filename) in loaders 57 | } 58 | 59 | function _transform( 60 | code: string, 61 | filename: string, 62 | options: TranspileOptions 63 | ): string { 64 | const loaders = getLoaders(options) 65 | const ret = transformSync(code, { 66 | ...commonOptions, 67 | ...(options.esbuild as TransformOptions | undefined), 68 | 69 | loader: loaders[path.extname(filename)], 70 | sourcefile: filename, 71 | }) 72 | return ret.code 73 | } 74 | 75 | function getLoaders(options: TranspileOptions) { 76 | const ret = { ...loaders } 77 | if (typeof options.esbuild?.loader == "object") { 78 | for (const [e, l] of Object.entries(options.esbuild.loader)) 79 | ret[e] = l as Loader 80 | } 81 | return ret 82 | } 83 | 84 | function _bundle( 85 | code: string, 86 | filename: string, 87 | options: TranspileOptions 88 | ): string { 89 | const ext = path.extname(filename) 90 | 91 | const loaders = getLoaders(options) 92 | 93 | return buildSync({ 94 | ...commonOptions, 95 | platform: "node", 96 | ...(options.esbuild as BuildOptions | undefined), 97 | loader: loaders, 98 | bundle: true, 99 | stdin: { 100 | sourcefile: filename, 101 | contents: code, 102 | resolveDir: path.dirname(filename), 103 | loader: loaders[ext], 104 | }, 105 | external: [...externals, ...(options?.esbuild?.external ?? [])], 106 | write: false, 107 | }) 108 | .outputFiles.map((f) => f.text) 109 | .join("\n") 110 | } 111 | 112 | export function transpile( 113 | code: string, 114 | filename: string, 115 | _options?: Partial 116 | ): string { 117 | const options: TranspileOptions = { ...defaultOptions, ..._options } 118 | if (options.type == "bundle") { 119 | // eslint-disable-next-line no-console 120 | if (options.debug) console.log(`📦 ${filename}`) 121 | return _bundle(code, filename, options) 122 | } else if (options.type == "transform") { 123 | return cache.get(filename, () => { 124 | // eslint-disable-next-line no-console 125 | if (options.debug) console.log(`📦 ${filename}`) 126 | return _transform(code, filename, options) 127 | }) 128 | } 129 | throw new Error(`Invalid transpilation option ${options.type}`) 130 | } 131 | -------------------------------------------------------------------------------- /src/hook.ts: -------------------------------------------------------------------------------- 1 | import InternalModule from "module" 2 | import { loaders, transpile, supports, TranspileOptions } from "./esbuild" 3 | import { install as installSourceMapSupport } from "source-map-support" 4 | import fs from "fs" 5 | import path from "path" 6 | 7 | type PatchedModule = InternalModule & { 8 | _extensions: Record void> 9 | _compile: (code: string, filename: string) => unknown 10 | } 11 | 12 | const Module = InternalModule as unknown as PatchedModule 13 | 14 | export function findUp(name: string, cwd = process.cwd()): string | undefined { 15 | let up = path.resolve(cwd) 16 | do { 17 | cwd = up 18 | const p = path.resolve(cwd, name) 19 | if (fs.existsSync(p)) return p 20 | up = path.resolve(cwd, "..") 21 | } while (up !== cwd) 22 | } 23 | 24 | function loadConfig() { 25 | const configFile = findUp("esbuild-runner.config.js") 26 | if (configFile) { 27 | try { 28 | // eslint-disable-next-line @typescript-eslint/no-var-requires, unicorn/prefer-module 29 | const ret = require(configFile) as TranspileOptions 30 | return ret 31 | } catch (error) { 32 | // eslint-disable-next-line no-console 33 | console.error( 34 | `[esbuild-runner] could not load "esbuild-runner.config.js"\n` 35 | ) 36 | throw error 37 | } 38 | } 39 | } 40 | 41 | export function install(options?: Partial) { 42 | options = { ...loadConfig(), ...options } 43 | installSourceMapSupport({ hookRequire: true }) 44 | const defaultLoaderJS = Module._extensions[".js"] 45 | for (const ext in loaders) { 46 | const defaultLoader = Module._extensions[ext] || defaultLoaderJS 47 | 48 | Module._extensions[ext] = (mod: PatchedModule, filename: string) => { 49 | if (supports(filename)) { 50 | const defaultCompile = mod._compile 51 | mod._compile = (code: string) => { 52 | mod._compile = defaultCompile 53 | return mod._compile(transpile(code, filename, options), filename) 54 | } 55 | } 56 | defaultLoader(mod, filename) 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./esbuild" 2 | export * from "./hook" 3 | -------------------------------------------------------------------------------- /src/jest.ts: -------------------------------------------------------------------------------- 1 | import { transpile } from "./esbuild" 2 | import "./register" 3 | 4 | function process(src: string, filename: string) { 5 | return { code: transpile(src, filename, { type: "transform" }) } 6 | } 7 | 8 | export default { process } 9 | -------------------------------------------------------------------------------- /src/register.ts: -------------------------------------------------------------------------------- 1 | import { install } from "./hook" 2 | install() 3 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": false, 4 | "allowSyntheticDefaultImports": true, 5 | "assumeChangesOnlyAffectDirectDependencies": true, 6 | "checkJs": false, 7 | "declaration": true, 8 | "emitDecoratorMetadata": true, 9 | "esModuleInterop": true, 10 | "experimentalDecorators": true, 11 | "importHelpers": true, 12 | "isolatedModules": false, 13 | "jsx": "preserve", 14 | "module": "CommonJS", 15 | "moduleResolution": "node", 16 | "noEmit": false, 17 | "resolveJsonModule": false, 18 | "skipLibCheck": true, 19 | "sourceMap": true, 20 | "strict": true, 21 | "target": "ES5", 22 | "outDir": "lib", 23 | "rootDir": "src", 24 | "types": ["node"] 25 | }, 26 | "include": ["src/**/*.ts"], 27 | "exclude": ["node_modules", "lib"] 28 | } 29 | --------------------------------------------------------------------------------