├── pnpm-workspace.yaml ├── eslint.config.js ├── .gitignore ├── test ├── __snapshots__ │ └── e2e.output.js ├── module-replacements.test.ts └── index.test.ts ├── playground ├── package.json └── index.js ├── tsconfig.json ├── .editorconfig ├── renovate.json ├── vitest.config.ts ├── .github ├── workflows │ ├── release.yml │ ├── provenance.yml │ ├── codeql.yml │ └── ci.yml └── ISSUE_TEMPLATE │ └── ---bug-report.yml ├── LICENCE ├── package.json ├── CODE_OF_CONDUCT.md ├── README.md └── src ├── index.ts └── replacements.ts /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - playground 3 | 4 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import antfu from '@antfu/eslint-config' 2 | 3 | export default antfu() 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | coverage 4 | .vscode 5 | .DS_Store 6 | .eslintcache 7 | *.log* 8 | *.env* 9 | -------------------------------------------------------------------------------- /test/__snapshots__/e2e.output.js: -------------------------------------------------------------------------------- 1 | var isString = v => typeof v === "string"; 2 | 3 | console.log(isString(3)); 4 | 5 | console.log(isString("")); 6 | -------------------------------------------------------------------------------- /playground/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "private": true, 4 | "scripts": { 5 | "dev": "node index.js" 6 | }, 7 | "dependencies": { 8 | "unplugin-purge-polyfills": "latest" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /playground/index.js: -------------------------------------------------------------------------------- 1 | import assert from 'node:assert' 2 | import * as pkg from 'unplugin-purge-polyfills' 3 | 4 | // eslint-disable-next-line no-console 5 | console.log(pkg.welcome()) 6 | 7 | assert.strictEqual(pkg.welcome(), 'hello world') 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "module": "ESNext", 5 | "moduleResolution": "Bundler", 6 | "strict": true, 7 | "esModuleInterop": true, 8 | "skipLibCheck": true 9 | }, 10 | "include": ["src", "test", "playground"] 11 | } 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | [*.js] 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [{package.json,*.yml,*.cjson}] 14 | indent_style = space 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "github>danielroe/renovate" 5 | ], 6 | "packageRules": [ 7 | { 8 | "packagePatterns": [ 9 | "module-replacements" 10 | ], 11 | "groupName": "module-replacements" 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { fileURLToPath } from 'node:url' 2 | import { defineConfig } from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | resolve: { 6 | alias: { 7 | 'unplugin-purge-polyfills': fileURLToPath( 8 | new URL('./src/index.ts', import.meta.url).href, 9 | ), 10 | }, 11 | }, 12 | test: { 13 | coverage: { 14 | include: ['src'], 15 | reporter: ['text', 'json', 'html'], 16 | }, 17 | }, 18 | }) 19 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - 'v*' 10 | 11 | jobs: 12 | release: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v6 16 | with: 17 | fetch-depth: 0 18 | 19 | - name: Set node 20 | uses: actions/setup-node@v6 21 | with: 22 | node-version: lts/-1 23 | 24 | - run: npx changelogithub 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | -------------------------------------------------------------------------------- /.github/workflows/provenance.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | permissions: 11 | contents: read 12 | jobs: 13 | check-provenance: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v6 17 | with: 18 | fetch-depth: 0 19 | - name: Check provenance downgrades 20 | uses: danielroe/provenance-action@41bcc969e579d9e29af08ba44fcbfdf95cee6e6c # v0.1.1 21 | with: 22 | fail-on-provenance-change: true 23 | -------------------------------------------------------------------------------- /test/module-replacements.test.ts: -------------------------------------------------------------------------------- 1 | import { microUtilsReplacements, nativeReplacements } from 'module-replacements' 2 | import { describe, expect, it } from 'vitest' 3 | 4 | import { defaultPolyfills } from '../src' 5 | 6 | describe('module-replacements', () => { 7 | const judgementCalls = [ 8 | 'for-each', 9 | 'hasown', 10 | 'has-own-prop', 11 | 'node.extend', 12 | 'extend-shallow', 13 | 'xtend', 14 | 'defaults', 15 | ] 16 | it.each(nativeReplacements.moduleReplacements)('has native $moduleName', (replacement) => { 17 | if (judgementCalls.includes(replacement.moduleName)) { 18 | return 19 | } 20 | expect(defaultPolyfills).toHaveProperty(replacement.moduleName) 21 | }) 22 | it.each(microUtilsReplacements.moduleReplacements)('has native $moduleName', (replacement) => { 23 | expect(defaultPolyfills).toHaveProperty(replacement.moduleName) 24 | }) 25 | }) 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---bug-report.yml: -------------------------------------------------------------------------------- 1 | name: 🐛 Bug report 2 | description: Something's not working 3 | labels: [bug] 4 | body: 5 | - type: textarea 6 | validations: 7 | required: true 8 | attributes: 9 | label: 🐛 The bug 10 | description: What isn't working? Describe what the bug is. 11 | - type: input 12 | validations: 13 | required: true 14 | attributes: 15 | label: 🛠️ To reproduce 16 | description: A reproduction of the bug via https://stackblitz.com/github/danielroe/unplugin-purge-polyfills/tree/main/playground 17 | placeholder: https://stackblitz.com/[...] 18 | - type: textarea 19 | validations: 20 | required: true 21 | attributes: 22 | label: 🌈 Expected behaviour 23 | description: What did you expect to happen? Is there a section in the docs about this? 24 | - type: textarea 25 | attributes: 26 | label: ℹ️ Additional context 27 | description: Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: CodeQL 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | schedule: 9 | - cron: '31 15 * * 5' 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ubuntu-latest 15 | permissions: 16 | actions: read 17 | contents: read 18 | security-events: write 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | language: [javascript] 24 | 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v6 28 | 29 | - name: Initialize CodeQL 30 | uses: github/codeql-action/init@v4 31 | with: 32 | languages: ${{ matrix.language }} 33 | queries: +security-and-quality 34 | 35 | - name: Autobuild 36 | uses: github/codeql-action/autobuild@v4 37 | 38 | - name: Perform CodeQL Analysis 39 | uses: github/codeql-action/analyze@v4 40 | with: 41 | category: '/language:${{ matrix.language }}' 42 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Daniel Roe 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 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | push: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | lint: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v6 17 | - run: corepack enable 18 | - uses: actions/setup-node@v6 19 | with: 20 | node-version: lts/-1 21 | cache: pnpm 22 | 23 | - name: 📦 Install dependencies 24 | run: pnpm install 25 | 26 | - name: 🔠 Lint project 27 | run: pnpm lint 28 | 29 | test: 30 | runs-on: ubuntu-latest 31 | 32 | steps: 33 | - uses: actions/checkout@v6 34 | - run: corepack enable 35 | - uses: actions/setup-node@v6 36 | with: 37 | node-version: lts/-1 38 | cache: pnpm 39 | 40 | - name: 📦 Install dependencies 41 | run: pnpm install 42 | 43 | - name: 🛠 Build project 44 | run: pnpm build 45 | 46 | - name: 💪 Test types 47 | run: pnpm test:types 48 | 49 | - name: 🧪 Test project 50 | run: pnpm test:unit --coverage 51 | 52 | - name: 🟩 Coverage 53 | uses: codecov/codecov-action@v5 54 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "unplugin-purge-polyfills", 3 | "type": "module", 4 | "version": "0.1.0", 5 | "packageManager": "pnpm@10.26.0", 6 | "description": "A tiny plugin to replace package imports with better native code.", 7 | "license": "MIT", 8 | "repository": "danielroe/unplugin-purge-polyfills", 9 | "sideEffects": false, 10 | "exports": { 11 | ".": "./dist/index.js" 12 | }, 13 | "main": "./dist/index.js", 14 | "module": "./dist/index.js", 15 | "types": "./dist/index.d.ts", 16 | "files": [ 17 | "dist" 18 | ], 19 | "scripts": { 20 | "build": "unbuild", 21 | "dev": "vitest dev", 22 | "lint": "eslint . --fix", 23 | "prepare": "simple-git-hooks", 24 | "prepack": "pnpm build", 25 | "prepublishOnly": "pnpm lint && pnpm test", 26 | "release": "bumpp && npm publish", 27 | "test": "pnpm test:unit && pnpm test:types", 28 | "test:unit": "vitest", 29 | "test:types": "tsc --noEmit" 30 | }, 31 | "dependencies": { 32 | "defu": "^6.1.4", 33 | "magic-string": "^0.30.17", 34 | "mlly": "^1.7.4", 35 | "unplugin": "^2.3.2" 36 | }, 37 | "devDependencies": { 38 | "@antfu/eslint-config": "latest", 39 | "@types/node": "24.10.4", 40 | "@vitest/coverage-v8": "latest", 41 | "bumpp": "10.3.2", 42 | "eslint": "latest", 43 | "lint-staged": "latest", 44 | "module-replacements": "2.1.0", 45 | "rollup": "4.53.4", 46 | "simple-git-hooks": "latest", 47 | "typescript": "latest", 48 | "unbuild": "latest", 49 | "vite": "7.3.0", 50 | "vitest": "latest" 51 | }, 52 | "resolutions": { 53 | "rollup": "4.53.4", 54 | "unplugin-purge-polyfills": "link:." 55 | }, 56 | "simple-git-hooks": { 57 | "pre-commit": "npx lint-staged" 58 | }, 59 | "lint-staged": { 60 | "*.{js,ts,mjs,cjs,json,.*rc}": [ 61 | "npx eslint --fix" 62 | ] 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [daniel@roe.dev](mailto:daniel@roe.dev). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 44 | 45 | [homepage]: https://www.contributor-covenant.org 46 | 47 | For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq 48 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import type { PurgePolyfillsOptions } from '../src' 2 | import { rollup } from 'rollup' 3 | import { describe, expect, it } from 'vitest' 4 | import { purgePolyfills } from '../src' 5 | 6 | describe('unplugin-purge-polyfills', () => { 7 | it('transforms raw code that uses polyfills', async () => { 8 | expect(await transform('const isString = isString("am I?")')).toMatchInlineSnapshot(`undefined`) 9 | expect(await transform(` 10 | const isString = require("is-string"); 11 | isString("am I?") 12 | `)).toMatchInlineSnapshot(` 13 | "const isString = v => typeof v === "string"; 14 | isString("am I?")" 15 | `) 16 | expect(await transform(` 17 | import isString from "is-string"; 18 | isString("am I?"); 19 | `)).toMatchInlineSnapshot(` 20 | "const isString = v => typeof v === "string"; 21 | isString("am I?");" 22 | `) 23 | }) 24 | 25 | it('does not transform non-JS files', async () => { 26 | expect(await transform(` 27 | const isString = require("is-string"); 28 | isString("am I?") 29 | `, {}, 'snappy.linux-x64-gnu.node')).toMatchInlineSnapshot(`undefined`) 30 | }) 31 | 32 | it('resolves polyfill imports', async () => { 33 | const code = await load('is-string') 34 | expect(code).toMatchInlineSnapshot(` 35 | "export default v => typeof v === "string" 36 | " 37 | `) 38 | }) 39 | 40 | it('does not duplicate polyfills', async () => { 41 | const bundle = await rollup({ 42 | input: 'entry.js', 43 | plugins: [ 44 | { 45 | name: 'entry', 46 | load: id => id === 'entry.js' ? 'import "other.js"; import isString from "is-string"; console.log(isString(""));' : undefined, 47 | resolveId: id => id === 'entry.js' ? id : undefined, 48 | }, 49 | { 50 | name: 'other', 51 | load: id => id === 'other.js' ? 'import isString from "is-string"; console.log(isString(3));' : undefined, 52 | resolveId: id => id === 'other.js' ? id : undefined, 53 | }, 54 | purgePolyfills.rollup({}), 55 | ], 56 | }) 57 | const { output } = await bundle.generate({ format: 'es' }) 58 | await expect(output[0].code).toMatchFileSnapshot('__snapshots__/e2e.output.js') 59 | }) 60 | }) 61 | 62 | function transform(code: string, opts: PurgePolyfillsOptions = { mode: 'transform' }, id = 'index.mjs'): Promise { 63 | const plugin = purgePolyfills.raw(opts, {} as any) 64 | // @ts-expect-error untyped 65 | const res = plugin.transform?.handler?.(code, id) 66 | return (res?.code ?? res ?? undefined)?.trim() 67 | } 68 | 69 | async function load(polyfillId: string, opts: PurgePolyfillsOptions = {}): Promise { 70 | return new Promise((resolve, reject) => { 71 | rollup({ 72 | input: 'entry.js', 73 | plugins: [ 74 | { 75 | name: 'entry', 76 | load: id => id === 'entry.js' ? id : undefined, 77 | resolveId: id => id === 'entry.js' ? id : undefined, 78 | }, 79 | { 80 | name: 'test-load', 81 | async transform(_code, id) { 82 | if (id === 'entry.js') { 83 | let error 84 | try { 85 | const res = await this.resolve(polyfillId) 86 | if (res) { 87 | const imp = await this.load(res) 88 | if (imp.code) { 89 | resolve(imp.code) 90 | return 91 | } 92 | } 93 | } 94 | catch (e) { 95 | error = e 96 | } 97 | reject(error || new Error(`Did not resolve polyfill import ${polyfillId}`)) 98 | } 99 | }, 100 | }, 101 | purgePolyfills.rollup(opts), 102 | ], 103 | }) 104 | }) 105 | } 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # unplugin-purge-polyfills 2 | 3 | [![npm version][npm-version-src]][npm-version-href] 4 | [![npm downloads][npm-downloads-src]][npm-downloads-href] 5 | [![Github Actions][github-actions-src]][github-actions-href] 6 | [![Codecov][codecov-src]][codecov-href] 7 | 8 | > A tiny plugin to replace package imports with better native code. 9 | 10 | This package is an [unplugin](https://unplugin.unjs.io/) which provides support for a wide range of bundlers. 11 | 12 | At build time, it removes usage of these packages, in favour of directly using native replacements: 13 | 14 | - is-number 15 | - is-plain-object 16 | - is-primitve 17 | - is-regexp 18 | - is-travis 19 | - is-npm 20 | - clone-regexp 21 | - split-lines 22 | - is-windows 23 | - is-whitespace 24 | - is-string 25 | - is-odd 26 | - is-even 27 | - object.entries 28 | - date 29 | - array.of 30 | - number.isnan 31 | - array.prototype.findindex 32 | - array.from 33 | - object-is 34 | - array-map 35 | - is-nan 36 | - function-bind 37 | - regexp.prototype.flags 38 | - array.prototype.find 39 | - object-keys 40 | - define-properties 41 | - left-pad 42 | - pad-left 43 | - filter-array 44 | - array-every 45 | - index-of 46 | - last-index-of 47 | - abort-controller 48 | - array-flatten 49 | - array-includes 50 | - has-own 51 | - has-proto 52 | - has-symbols 53 | - object-assign 54 | - call-bind 55 | - es-get-iterator 56 | - es-set-tostringtag 57 | - is-array-buffer 58 | - is-boolean-object 59 | - is-date-object 60 | - is-negative-zero 61 | - is-number-object 62 | - is-primitive 63 | 64 | It is under active development. 65 | 66 | ## Roadmap 67 | 68 | - [ ] investigate tighter integration with https://github.com/SukkaW/nolyfill or https://github.com/es-tooling/module-replacements 69 | - [ ] implement publish-on-demand infrastructure to apply this plugin to published packages 70 | 71 | ## Usage 72 | 73 | Install package: 74 | 75 | ```sh 76 | # npm 77 | npm install --save-dev unplugin-purge-polyfills 78 | ``` 79 | 80 | ```js 81 | import { purgePolyfills } from 'unplugin-purge-polyfills' 82 | 83 | // rollup.config.js 84 | export default { 85 | plugins: [ 86 | purgePolyfills.rollup({ /* options */ }), 87 | ], 88 | } 89 | ``` 90 | 91 | ## Configuration 92 | 93 | By default this unplugin ships with a wide range of polyfills to get rid of, but you can disable these and add your own by providing a `replacements` object: 94 | 95 | ```js 96 | // rollup.config.js 97 | export default { 98 | plugins: [ 99 | purgePolyfills.rollup({ 100 | replacements: { 101 | 'is-string': false, /** do not provide this polyfill */ 102 | /** 103 | * provide a custom polyfill for this import in your codebase 104 | * make sure this is correct for every usage 105 | */ 106 | 'node.extend': { 107 | default: '(obj1, obj2) => { ...obj2, ...obj1 }' 108 | } 109 | } 110 | }), 111 | ], 112 | } 113 | ``` 114 | 115 | The following polyfills are not purged, so you might want to add your own code to do so: 116 | 117 | - node.extend 118 | - extend-shallow 119 | - xtend 120 | - defaults 121 | 122 | ## Projects using or experimenting with `unplugin-purge-polyfill` 123 | 124 | - [nuxt/cli](https://github.com/nuxt/cli/pull/439) 125 | - [unjs/jiti](https://github.com/unjs/jiti/pull/261) 126 | 127 | ## Credits 128 | 129 | Thanks to https://github.com/es-tooling/module-replacements and https://github.com/esm-dev/esm.sh for polyfill data. ❤️ 130 | 131 | Inspiration from https://github.com/SukkaW/nolyfill. ❤️ 132 | 133 | ## 💻 Development 134 | 135 | - Clone this repository 136 | - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` 137 | - Install dependencies using `pnpm install` 138 | - Run interactive tests using `pnpm dev` 139 | 140 | ## License 141 | 142 | Made with ❤️ 143 | 144 | Published under [MIT License](./LICENCE). 145 | 146 | 147 | 148 | [npm-version-src]: https://img.shields.io/npm/v/unplugin-purge-polyfills?style=flat-square 149 | [npm-version-href]: https://npmjs.com/package/unplugin-purge-polyfills 150 | [npm-downloads-src]: https://img.shields.io/npm/dm/unplugin-purge-polyfills?style=flat-square 151 | [npm-downloads-href]: https://npm.chart.dev/unplugin-purge-polyfills 152 | [github-actions-src]: https://img.shields.io/github/actions/workflow/status/danielroe/unplugin-purge-polyfills/ci.yml?branch=main&style=flat-square 153 | [github-actions-href]: https://github.com/danielroe/unplugin-purge-polyfills/actions/workflows/ci.yml 154 | [codecov-src]: https://img.shields.io/codecov/c/gh/danielroe/unplugin-purge-polyfills/main?style=flat-square 155 | [codecov-href]: https://codecov.io/gh/danielroe/unplugin-purge-polyfills 156 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import type { UnpluginOptions } from 'unplugin' 2 | import { defu } from 'defu' 3 | import MagicString from 'magic-string' 4 | import { findStaticImports, parseStaticImport } from 'mlly' 5 | import { createUnplugin } from 'unplugin' 6 | 7 | import { defaultPolyfills } from './replacements' 8 | 9 | export { defaultPolyfills } from './replacements' 10 | 11 | export interface PurgePolyfillsOptions { 12 | sourcemap?: boolean 13 | replacements?: Record> 14 | logLevel?: 'quiet' | 'verbose' 15 | mode?: 'load' | 'transform' 16 | /** 17 | * An array of patterns to match source files against when running in `transform` mode 18 | * @default [/\.[cm][tj]sx?$/] 19 | */ 20 | include?: Array 21 | /** An array of patterns to exclude source files when running in `transform` mode */ 22 | exclude?: Array 23 | } 24 | 25 | const CJS_STATIC_IMPORT_RE = /(?<=\s|^|[;}])(const|var|let)((?[\p{L}\p{M}\w\t\n\r $*,/{}@.]+))=\s*require\(["']\s*(?(?<=")[^"]*[^\s"](?=\s*")|(?<=')[^']*[^\s'](?=\s*'))\s*["']\)[\s;]*/gmu 26 | 27 | const VIRTUAL_POLYFILL_PREFIX = 'virtual:purge-polyfills:' 28 | 29 | export const purgePolyfills = createUnplugin((opts = {}) => { 30 | const _knownMods = defu(opts.replacements, defaultPolyfills) 31 | // Allow passing `false` to disable a polyfill 32 | for (const mod in _knownMods) { 33 | if (!_knownMods[mod]) { 34 | delete _knownMods[mod] 35 | } 36 | } 37 | const knownMods = _knownMods as Record> 38 | const specifiers = new Set(Object.keys(knownMods)) 39 | 40 | const logs = new Set() 41 | 42 | function load(id: string) { 43 | if (id.startsWith(VIRTUAL_POLYFILL_PREFIX)) { 44 | const polyfillId = id.slice(VIRTUAL_POLYFILL_PREFIX.length) 45 | let code = '' 46 | for (const exportName in knownMods[polyfillId]) { 47 | if (exportName === 'default') { 48 | code += `export default ${knownMods[polyfillId].default}\n` 49 | continue 50 | } 51 | code += `export const ${exportName} = ${knownMods[polyfillId][exportName]}\n` 52 | } 53 | logs.add(`Replaced import from ${polyfillId}.`) 54 | return code 55 | } 56 | } 57 | 58 | function resolveId(id: string) { 59 | if (specifiers.has(id)) { 60 | return VIRTUAL_POLYFILL_PREFIX + id 61 | } 62 | } 63 | 64 | function transform(code: string) { 65 | const staticImports = findStaticImports(code) 66 | for (const match of code.matchAll(CJS_STATIC_IMPORT_RE)) { 67 | staticImports.push({ 68 | type: 'static', 69 | ...match.groups as { imports: string, specifier: string }, 70 | code: match[0], 71 | start: match.index, 72 | end: (match.index || 0) + match[0].length, 73 | }) 74 | } 75 | 76 | if (!staticImports.length) 77 | return 78 | 79 | const polyfillImports = staticImports.filter(i => specifiers.has(i.specifier)) 80 | if (!polyfillImports.length) 81 | return 82 | 83 | const s = new MagicString(code) 84 | for (const polyfillImport of polyfillImports) { 85 | const parsed = parseStaticImport(polyfillImport) 86 | let code = '' 87 | const names = parsed.namedImports || {} 88 | if (parsed.defaultImport) { 89 | names.default = parsed.defaultImport 90 | } 91 | 92 | for (const p in names) { 93 | const replacement = knownMods[polyfillImport.specifier]?.[p] 94 | if (replacement) { 95 | code += `const ${names[p]} = ${replacement};\n` 96 | } 97 | logs.add(`Inlined replacement from ${polyfillImport.specifier}.`) 98 | } 99 | 100 | s.overwrite(polyfillImport.start, polyfillImport.end, code) 101 | } 102 | 103 | if (s.hasChanged()) { 104 | return { 105 | code: s.toString(), 106 | map: opts.sourcemap ? s.generateMap(({ hires: true })) : null, 107 | } 108 | } 109 | } 110 | 111 | return { 112 | name: 'unplugin-purge-polyfills', 113 | ...(opts.mode === 'transform' 114 | ? { 115 | transform: { 116 | filter: { 117 | id: { 118 | include: opts.include || [/\.[cm][tj]sx?$/], 119 | exclude: opts.exclude, 120 | }, 121 | }, 122 | handler: transform, 123 | }, 124 | } 125 | : { 126 | resolveId, 127 | load, 128 | }), 129 | buildEnd() { 130 | if (opts.logLevel === 'quiet') { 131 | return 132 | } 133 | if (opts.logLevel === 'verbose') { 134 | for (const log of logs) { 135 | // eslint-disable-next-line no-console 136 | console.log(log) 137 | } 138 | // eslint-disable-next-line no-console 139 | console.log(`Purged ${logs.size} polyfills.`) 140 | } 141 | }, 142 | } satisfies UnpluginOptions 143 | }) 144 | -------------------------------------------------------------------------------- /src/replacements.ts: -------------------------------------------------------------------------------- 1 | export const defaultPolyfills: Record> = { 2 | // Micro-utilities 3 | 'call-bind': { 4 | default: 'v => Function.call.bind(v)', 5 | }, 6 | 'clone-regexp': { 7 | default: 'v => new RegExp(v)', 8 | }, 9 | 'es-get-iterator': { 10 | default: 'v => v[Symbol.iterator]?.()', 11 | }, 12 | 'es-set-tostringtag': { 13 | default: '(target, value) => Object.defineProperty(target, Symbol.toStringTag, { value, configurable: true })', 14 | }, 15 | 'is-array-buffer': { 16 | default: 'v => Object.prototype.toString.call(v) === "[object ArrayBuffer]"', 17 | }, 18 | 'is-boolean-object': { 19 | default: 'v => Object.prototype.toString.call(v) === "[object Boolean]"', 20 | }, 21 | 'is-date-object': { 22 | default: 'v => Object.prototype.toString.call(v) === "[object Date]"', 23 | }, 24 | 'is-even': { 25 | default: 'n => (n % 2) === 0', 26 | }, 27 | 'is-negative-zero': { 28 | default: 'v => Object.is(v, -0)', 29 | }, 30 | 'is-npm': { 31 | default: '() => process.env.npm_config_user_agent?.startsWith("npm")', 32 | }, 33 | 'is-number': { 34 | default: 'v => typeof v === "number"', 35 | }, 36 | 'is-number-object': { 37 | default: 'v => Object.prototype.toString.call(v) === "[object Number]"', 38 | }, 39 | 'is-odd': { 40 | default: 'n => (n % 2) === 1', 41 | }, 42 | 'is-plain-object': { 43 | default: 'v => typeof v === "object" && v !== null && v.constructor === Object', 44 | }, 45 | 'is-primitive': { 46 | default: 'v => v === null || (typeof v !== "function" && typeof v !== "object")', 47 | }, 48 | 'is-primitve': { 49 | default: 'v => v === null || (typeof v !== "function" && typeof v !== "object")', 50 | }, 51 | 'is-regexp': { 52 | default: 'v => Object.prototype.toString.call(v) === "[object RegExp]"', 53 | }, 54 | 'is-string': { 55 | default: 'v => typeof v === "string"', 56 | }, 57 | 'is-travis': { 58 | default: '() => "TRAVIS" in process.env', 59 | }, 60 | 'is-whitespace': { 61 | default: 'str => str.trim() === ""', 62 | }, 63 | 'is-windows': { 64 | default: '() => process.platform === "win32"', 65 | }, 66 | 'split-lines': { 67 | default: 'str => str.split(/\\r?\\n/)', 68 | }, 69 | // native replacements 70 | 'array-every': { 71 | default: 'Array.prototype.every', 72 | }, 73 | 'array-map': { 74 | default: 'Array.prototype.map', 75 | }, 76 | 'array.from': { 77 | default: 'Array.from', 78 | }, 79 | 'array.of': { 80 | default: 'Array.of', 81 | }, 82 | 'array.prototype.find': { 83 | default: 'Array.prototype.find', 84 | }, 85 | 'array.prototype.findindex': { 86 | default: 'Array.prototype.findIndex', 87 | }, 88 | 'date': { 89 | default: 'Date', 90 | }, 91 | 'define-properties': { 92 | default: 'Object.defineProperties', 93 | }, 94 | 'filter-array': { 95 | default: 'Array.prototype.filter', 96 | }, 97 | 'function-bind': { 98 | default: 'Function.prototype.bind', 99 | }, 100 | 'has-own-prop': { 101 | default: 'Object.hasOwn ?? ((o, p) => Object.prototype.hasOwnProperty.call(o, p))', 102 | }, 103 | 'hasown': { 104 | default: '(obj, prop) => obj.hasOwnProperty(prop)', 105 | }, 106 | 'index-of': { 107 | default: 'Array.prototype.indexOf', 108 | }, 109 | 'is-nan': { 110 | default: 'Number.isNaN', 111 | }, 112 | 'last-index-of': { 113 | default: 'Array.prototype.lastIndexOf', 114 | }, 115 | 'left-pad': { 116 | default: 'String.prototype.padStart', 117 | }, 118 | 'number.isnan': { 119 | default: 'Number.isNaN', 120 | }, 121 | 'object-is': { 122 | default: 'Object.is', 123 | }, 124 | 'object-keys': { 125 | default: 'Object.keys', 126 | }, 127 | 'object.entries': { 128 | default: 'Object.entries', 129 | }, 130 | 'pad-left': { 131 | default: 'String.prototype.padStart', 132 | }, 133 | 'regexp.prototype.flags': { 134 | default: 'RegExp.prototype.flags', 135 | }, 136 | // https://github.com/esm-dev/esm.sh/blob/main/server/embed/polyfills 137 | 'abort-controller': { 138 | AbortSignal: 'AbortSignal', 139 | AbortController: 'AbortController', 140 | default: 'AbortController', 141 | }, 142 | 'array-flatten': { 143 | default: '(a, d) => a.flat(typeof d < "u" ? d : Infinity)', 144 | }, 145 | 'array-includes': { 146 | default: '(a, p, i) => a.includes(p, i)', 147 | }, 148 | 'has-own': { 149 | default: 'Object.hasOwn', 150 | }, 151 | 'has-proto': { 152 | default: '() => { const foo = { bar: {} }; return ({ __proto__: foo }).bar === foo.bar && !({ __proto__: null } instanceof Object) }', 153 | }, 154 | 'has-symbols': { 155 | default: '() => true', 156 | }, 157 | 'object-assign': { 158 | default: 'Object.assign', 159 | }, 160 | // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore/blob/master/lib/rules/rules.json 161 | 'lodash.capitalize': { 162 | default: 'string.charAt(0).toUpperCase() + string.slice(1).toLowerCase()', 163 | }, 164 | 'lodash.castArray': { 165 | default: 'Array.isArray(arr) ? arr : [arr]', 166 | }, 167 | 'lodash.cloneDeep': { 168 | default: 'structuredClone()', 169 | }, 170 | 'lodash.concat': { 171 | default: 'Array.prototype.concat', 172 | }, 173 | 'lodash.defaults': { 174 | default: 'Object.assign({}, defaultValues, newValues)', 175 | }, 176 | 'lodash.detect': { 177 | default: 'Array.prototype.find', 178 | }, 179 | 'lodash.drop': { 180 | default: '(arr, n = 1) => arr.slice(n)', 181 | }, 182 | 'lodash.dropRight': { 183 | default: '(arr, n = 1) => arr.slice(0, -n || arr.length)', 184 | }, 185 | 'lodash.endsWith': { 186 | default: 'String.prototype.endsWith', 187 | }, 188 | 'lodash.fill': { 189 | default: 'Array.prototype.fill', 190 | }, 191 | 'lodash.first': { 192 | default: 'arr => arr.at(0) || arr[0]', 193 | }, 194 | 'lodash.flatten': { 195 | default: 'Array.prototype.reduce((a, b) => a.concat(b), [])', 196 | }, 197 | 'lodash.head': { 198 | default: 'Array.prototype.at(0)', 199 | }, 200 | 'lodash.isArrayBuffer': { 201 | default: 'value instanceof ArrayBuffer', 202 | }, 203 | 'lodash.isDate': { 204 | default: 'String.prototype.toString.call()', 205 | }, 206 | 'lodash.isFunction': { 207 | default: 'typeof func === "function"', 208 | }, 209 | 'lodash.isString': { 210 | default: 'str != null && typeof str.valueOf() === "string"', 211 | }, 212 | 'lodash.join': { 213 | default: 'Array.prototype.join', 214 | }, 215 | 'lodash.last': { 216 | default: 'arr => arr.at(-1) || arr[arr.length - 1]', 217 | }, 218 | 'lodash.omit': { 219 | default: '{a, b, c, ...notOmittedValues}', 220 | }, 221 | 'lodash.padEnd': { 222 | default: 'String.prototype.padEnd', 223 | }, 224 | 'lodash.repeat': { 225 | default: 'String.prototype.repeat', 226 | }, 227 | 'lodash.replace': { 228 | default: 'String.prototype.replace', 229 | }, 230 | 'lodash.reverse': { 231 | default: 'Array.prototype.reverse', 232 | }, 233 | 'lodash.split': { 234 | default: 'String.prototype.split', 235 | }, 236 | 'lodash.startsWith': { 237 | default: 'String.prototype.startsWith', 238 | }, 239 | 'lodash.toLower': { 240 | default: 'String.prototype.toLowerCase', 241 | }, 242 | 'lodash.toUpper': { 243 | default: 'String.prototype.toUpperCase', 244 | }, 245 | 'lodash.trim': { 246 | default: 'String.prototype.trim', 247 | }, 248 | 'lodash.uniq': { 249 | default: '[... new Set(arr)]', 250 | }, 251 | } 252 | --------------------------------------------------------------------------------