From c7c331c75e98b90808a14bd7cdee37f37fb80765 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90?= Date: Sat, 29 Oct 2022 15:25:18 +0800 Subject: [PATCH 1/3] chore: switch to @antfu/eslint-config --- .eslintrc | 8 +- package.json | 8 +- pnpm-lock.yaml | 481 +++++++++++------- scripts/buildFixtures.ts | 12 +- src/define.ts | 23 +- src/esbuild/index.ts | 84 ++- src/esbuild/utils.ts | 50 +- src/rollup/index.ts | 21 +- src/types.ts | 38 +- src/utils.ts | 12 +- src/vite/index.ts | 12 +- src/webpack/context.ts | 28 +- src/webpack/index.ts | 86 ++-- src/webpack/loaders/load.ts | 21 +- src/webpack/loaders/transform.ts | 19 +- .../fixtures/transform/__test__/build.test.ts | 2 +- .../virtual-module/__test__/build.test.ts | 2 +- .../id-consistency/id-consistency.test.ts | 40 +- .../resolve-id-external.test.ts | 32 +- test/unit-tests/resolve-id/resolve-id.test.ts | 34 +- test/unit-tests/utils.ts | 2 +- .../write-bundle/write-bundle.test.ts | 38 +- tsup.config.ts | 8 +- vitest.config.ts | 8 +- 24 files changed, 581 insertions(+), 488 deletions(-) diff --git a/.eslintrc b/.eslintrc index 1cfadd21..188e9ba7 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,9 +1,3 @@ { - "extends": [ - "@nuxtjs/eslint-config-typescript" - ], - "rules": { - "no-use-before-define": "off", - "import/no-named-as-default-member": "off" - } + "extends": ["@antfu"] } diff --git a/package.json b/package.json index 67743f6a..4a7c6783 100644 --- a/package.json +++ b/package.json @@ -3,13 +3,13 @@ "version": "0.10.2", "packageManager": "pnpm@7.14.0", "description": "Unified plugin system for build tools", - "repository": "unjs/unplugin", "license": "MIT", + "repository": "unjs/unplugin", "sideEffects": false, "exports": { ".": { - "import": "./dist/index.mjs", - "require": "./dist/index.js" + "require": "./dist/index.js", + "import": "./dist/index.mjs" }, "./dist/webpack/loaders/load": "./dist/webpack/loaders/load.js", "./dist/webpack/loaders/transform": "./dist/webpack/loaders/transform.js" @@ -37,8 +37,8 @@ }, "devDependencies": { "@ampproject/remapping": "^2.2.0", + "@antfu/eslint-config": "^0.27.0", "@antfu/ni": "^0.18.3", - "@nuxtjs/eslint-config-typescript": "^11.0.0", "@types/express": "^4.17.14", "@types/fs-extra": "^9.0.13", "@types/node": "^18.11.5", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b1547da6..6370c1ce 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2,8 +2,8 @@ lockfileVersion: 5.4 specifiers: '@ampproject/remapping': ^2.2.0 + '@antfu/eslint-config': ^0.27.0 '@antfu/ni': ^0.18.3 - '@nuxtjs/eslint-config-typescript': ^11.0.0 '@types/express': ^4.17.14 '@types/fs-extra': ^9.0.13 '@types/node': ^18.11.5 @@ -38,8 +38,8 @@ dependencies: devDependencies: '@ampproject/remapping': 2.2.0 + '@antfu/eslint-config': 0.27.0_wyqvi574yv7oiwfeinomdzmc3m '@antfu/ni': 0.18.3 - '@nuxtjs/eslint-config-typescript': 11.0.0_wyqvi574yv7oiwfeinomdzmc3m '@types/express': 4.17.14 '@types/fs-extra': 9.0.13 '@types/node': 18.11.5 @@ -72,6 +72,91 @@ packages: '@jridgewell/trace-mapping': 0.3.9 dev: true + /@antfu/eslint-config-basic/0.27.0_gxwdnffpiv5ciyba5kqrxpisdq: + resolution: {integrity: sha512-QgQVCiNiV9ZF7h09uBqTHctHDfVqJGIIpe0ZHCicLvUv233nAYeu4adAr53buhKrxDeoalozSs2ePiDiCyceTg==} + peerDependencies: + eslint: '>=7.4.0' + dependencies: + eslint: 8.26.0 + eslint-plugin-antfu: 0.27.0_wyqvi574yv7oiwfeinomdzmc3m + eslint-plugin-eslint-comments: 3.2.0_eslint@8.26.0 + eslint-plugin-html: 7.1.0 + eslint-plugin-import: 2.26.0_r2qesmvbtasnioxvcewzbti7fm + eslint-plugin-jsonc: 2.5.0_eslint@8.26.0 + eslint-plugin-markdown: 3.0.0_eslint@8.26.0 + eslint-plugin-n: 15.2.5_eslint@8.26.0 + eslint-plugin-promise: 6.0.1_eslint@8.26.0 + eslint-plugin-unicorn: 43.0.2_eslint@8.26.0 + eslint-plugin-yml: 1.2.0_eslint@8.26.0 + jsonc-eslint-parser: 2.1.0 + yaml-eslint-parser: 1.1.0 + transitivePeerDependencies: + - '@typescript-eslint/parser' + - eslint-import-resolver-typescript + - eslint-import-resolver-webpack + - supports-color + - typescript + dev: true + + /@antfu/eslint-config-ts/0.27.0_wyqvi574yv7oiwfeinomdzmc3m: + resolution: {integrity: sha512-h/ai9xe65lXtsUiSBRAvfcN47fqn5uGHcCA5c0LoBRX6fVFHk06BbPWMlSJRtqmc3uBTmv3gU8SrnWwrycnKag==} + peerDependencies: + eslint: '>=7.4.0' + typescript: '>=3.9' + dependencies: + '@antfu/eslint-config-basic': 0.27.0_gxwdnffpiv5ciyba5kqrxpisdq + '@typescript-eslint/eslint-plugin': 5.36.2_gxwdnffpiv5ciyba5kqrxpisdq + '@typescript-eslint/parser': 5.36.2_wyqvi574yv7oiwfeinomdzmc3m + eslint: 8.26.0 + typescript: 4.8.4 + transitivePeerDependencies: + - eslint-import-resolver-typescript + - eslint-import-resolver-webpack + - supports-color + dev: true + + /@antfu/eslint-config-vue/0.27.0_wyqvi574yv7oiwfeinomdzmc3m: + resolution: {integrity: sha512-Iw4GY4rXK1dPxzIl35bOwPE1vn6E5Wm8uljqdpQYQpTX1j6el7Yo30bpanCogWRcdPSMWKcS7GVlHjV47QB59w==} + peerDependencies: + eslint: '>=7.4.0' + dependencies: + '@antfu/eslint-config-ts': 0.27.0_wyqvi574yv7oiwfeinomdzmc3m + eslint: 8.26.0 + eslint-plugin-vue: 9.4.0_eslint@8.26.0 + transitivePeerDependencies: + - eslint-import-resolver-typescript + - eslint-import-resolver-webpack + - supports-color + - typescript + dev: true + + /@antfu/eslint-config/0.27.0_wyqvi574yv7oiwfeinomdzmc3m: + resolution: {integrity: sha512-xM1In6/ueNyKxxWO86jd7a9IdKby66lZVT/fE8k2RlP+X0xe5/DTTQfwLbVvnRpn77jCPIhEjNKVWxDO/DUEIg==} + peerDependencies: + eslint: '>=7.4.0' + dependencies: + '@antfu/eslint-config-vue': 0.27.0_wyqvi574yv7oiwfeinomdzmc3m + '@typescript-eslint/eslint-plugin': 5.36.2_gxwdnffpiv5ciyba5kqrxpisdq + '@typescript-eslint/parser': 5.36.2_wyqvi574yv7oiwfeinomdzmc3m + eslint: 8.26.0 + eslint-plugin-eslint-comments: 3.2.0_eslint@8.26.0 + eslint-plugin-html: 7.1.0 + eslint-plugin-import: 2.26.0_r2qesmvbtasnioxvcewzbti7fm + eslint-plugin-jsonc: 2.5.0_eslint@8.26.0 + eslint-plugin-n: 15.2.5_eslint@8.26.0 + eslint-plugin-promise: 6.0.1_eslint@8.26.0 + eslint-plugin-unicorn: 43.0.2_eslint@8.26.0 + eslint-plugin-vue: 9.4.0_eslint@8.26.0 + eslint-plugin-yml: 1.2.0_eslint@8.26.0 + jsonc-eslint-parser: 2.1.0 + yaml-eslint-parser: 1.1.0 + transitivePeerDependencies: + - eslint-import-resolver-typescript + - eslint-import-resolver-webpack + - supports-color + - typescript + dev: true + /@antfu/ni/0.18.3: resolution: {integrity: sha512-Tjn/lApBYvQhFCw0GgJIdENOk1m6LxucvPqBnCfWQRc2tI+uxtAvJljxiSR9s5B/gtMahGBsB6Hs7H8HZIOY6Q==} hasBin: true @@ -228,55 +313,6 @@ packages: fastq: 1.13.0 dev: true - /@nuxtjs/eslint-config-typescript/11.0.0_wyqvi574yv7oiwfeinomdzmc3m: - resolution: {integrity: sha512-hmFjGtXT524ql8eTbK8BaRkamcXB6Z8YOW8nSQhosTP6oBw9WtOFUeWr7holyE278UhOmx+wDFG90BnyM9D+UA==} - peerDependencies: - eslint: ^8.23.0 - dependencies: - '@nuxtjs/eslint-config': 11.0.0_3kfy4n2yrit4yqblnsz4zmqkii - '@typescript-eslint/eslint-plugin': 5.36.2_gxwdnffpiv5ciyba5kqrxpisdq - '@typescript-eslint/parser': 5.36.2_wyqvi574yv7oiwfeinomdzmc3m - eslint: 8.26.0 - eslint-import-resolver-typescript: 3.5.1_mynvxvmq5qtyojffiqgev4x7mm - eslint-plugin-import: 2.26.0_3kfy4n2yrit4yqblnsz4zmqkii - transitivePeerDependencies: - - eslint-import-resolver-webpack - - supports-color - - typescript - dev: true - - /@nuxtjs/eslint-config/11.0.0_3kfy4n2yrit4yqblnsz4zmqkii: - resolution: {integrity: sha512-o4zFOpU8gJgwrC/gLE7c2E0XEjkv2fEixCGG1y+dZYzBPyzTorkQmfxskSF3WRXcZkpkS9uUYlRkeOSdYB7z0w==} - peerDependencies: - eslint: ^8.23.0 - dependencies: - eslint: 8.26.0 - eslint-config-standard: 17.0.0_6cmbzicqlx7slyu26nv6kzji4y - eslint-plugin-import: 2.26.0_3kfy4n2yrit4yqblnsz4zmqkii - eslint-plugin-n: 15.2.5_eslint@8.26.0 - eslint-plugin-node: 11.1.0_eslint@8.26.0 - eslint-plugin-promise: 6.0.1_eslint@8.26.0 - eslint-plugin-unicorn: 43.0.2_eslint@8.26.0 - eslint-plugin-vue: 9.4.0_eslint@8.26.0 - transitivePeerDependencies: - - '@typescript-eslint/parser' - - eslint-import-resolver-typescript - - eslint-import-resolver-webpack - - supports-color - dev: true - - /@pkgr/utils/2.3.1: - resolution: {integrity: sha512-wfzX8kc1PMyUILA+1Z/EqoE4UCXGy0iRGMhPwdfae1+f0OXlLqCk+By+aMzgJBzR9AzS4CDizioG6Ss1gvAFJw==} - engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} - dependencies: - cross-spawn: 7.0.3 - is-glob: 4.0.3 - open: 8.4.0 - picocolors: 1.0.0 - tiny-glob: 0.2.9 - tslib: 2.4.0 - dev: true - /@types/body-parser/1.19.2: resolution: {integrity: sha512-ALYone6pm6QmwZoAgeyNksccT9Q4AWZQ6PvfwR37GT6r6FWUPguq6sUmNGSMV2Wr761oQoBxwGGa6DR5o1DC9g==} dependencies: @@ -349,6 +385,12 @@ packages: resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==} dev: true + /@types/mdast/3.0.10: + resolution: {integrity: sha512-W864tg/Osz1+9f4lrGTZpCSO5/z4608eUp19tbozkq2HJK6i3z1kT0H9tlADXuYIb1YYOBByU4Jsqkk75q48qA==} + dependencies: + '@types/unist': 2.0.6 + dev: true + /@types/mime/1.3.2: resolution: {integrity: sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==} dev: true @@ -384,6 +426,10 @@ packages: resolution: {integrity: sha512-K5K+yml8LTo9bWJI/rECfIPrGgxdpeNbj+d53lwN4QjW1MCwlkhUms+gtdzigTeUyBr09+u8BwOIY3MXvHdcsA==} dev: true + /@types/unist/2.0.6: + resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==} + dev: true + /@types/webpack-sources/3.2.0: resolution: {integrity: sha512-Ft7YH3lEVRQ6ls8k4Ff1oB4jN6oy/XmU6tQISKdhfh+1mR+viZFphS6WL0IrtDOzvefmJg5a0s7ZQoRXwqTEFg==} dependencies: @@ -930,6 +976,18 @@ packages: supports-color: 7.2.0 dev: true + /character-entities-legacy/1.1.4: + resolution: {integrity: sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA==} + dev: true + + /character-entities/1.2.4: + resolution: {integrity: sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw==} + dev: true + + /character-reference-invalid/1.1.4: + resolution: {integrity: sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==} + dev: true + /check-error/1.0.2: resolution: {integrity: sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==} dev: true @@ -1275,11 +1333,6 @@ packages: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} dev: true - /define-lazy-prop/2.0.0: - resolution: {integrity: sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==} - engines: {node: '>=8'} - dev: true - /define-properties/1.1.3: resolution: {integrity: sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==} engines: {node: '>= 0.4'} @@ -1308,6 +1361,33 @@ packages: esutils: 2.0.3 dev: true + /dom-serializer/2.0.0: + resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + entities: 4.4.0 + dev: true + + /domelementtype/2.3.0: + resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} + dev: true + + /domhandler/5.0.3: + resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} + engines: {node: '>= 4'} + dependencies: + domelementtype: 2.3.0 + dev: true + + /domutils/3.0.1: + resolution: {integrity: sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==} + dependencies: + dom-serializer: 2.0.0 + domelementtype: 2.3.0 + domhandler: 5.0.3 + dev: true + /dot-prop/5.3.0: resolution: {integrity: sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==} engines: {node: '>=8'} @@ -1331,6 +1411,11 @@ packages: tapable: 2.2.1 dev: true + /entities/4.4.0: + resolution: {integrity: sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==} + engines: {node: '>=0.12'} + dev: true + /envinfo/7.8.1: resolution: {integrity: sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==} engines: {node: '>=4'} @@ -1607,20 +1692,6 @@ packages: engines: {node: '>=10'} dev: true - /eslint-config-standard/17.0.0_6cmbzicqlx7slyu26nv6kzji4y: - resolution: {integrity: sha512-/2ks1GKyqSOkH7JFvXJicu0iMpoojkwB+f5Du/1SC0PtBL+s8v30k9njRZ21pm2drKYm2342jFnGWzttxPmZVg==} - peerDependencies: - eslint: ^8.0.1 - eslint-plugin-import: ^2.25.2 - eslint-plugin-n: ^15.0.0 - eslint-plugin-promise: ^6.0.0 - dependencies: - eslint: 8.26.0 - eslint-plugin-import: 2.26.0_3kfy4n2yrit4yqblnsz4zmqkii - eslint-plugin-n: 15.2.5_eslint@8.26.0 - eslint-plugin-promise: 6.0.1_eslint@8.26.0 - dev: true - /eslint-import-resolver-node/0.3.6: resolution: {integrity: sha512-0En0w03NRVMn9Uiyn8YRPDKvWjxCWkslUEhGNTdGx15RvPJYQ+lbOlqrlNI2vEAs4pDYK4f/HN2TbDmk5TP0iw==} dependencies: @@ -1630,27 +1701,7 @@ packages: - supports-color dev: true - /eslint-import-resolver-typescript/3.5.1_mynvxvmq5qtyojffiqgev4x7mm: - resolution: {integrity: sha512-U7LUjNJPYjNsHvAUAkt/RU3fcTSpbllA0//35B4eLYTX74frmOepbt7F7J3D1IGtj9k21buOpaqtDd4ZlS/BYQ==} - engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} - peerDependencies: - eslint: '*' - eslint-plugin-import: '*' - dependencies: - debug: 4.3.4 - enhanced-resolve: 5.10.0 - eslint: 8.26.0 - eslint-plugin-import: 2.26.0_3kfy4n2yrit4yqblnsz4zmqkii - get-tsconfig: 4.2.0 - globby: 13.1.2 - is-core-module: 2.10.0 - is-glob: 4.0.3 - synckit: 0.8.4 - transitivePeerDependencies: - - supports-color - dev: true - - /eslint-module-utils/2.7.3_7liths4w263er5tix7tpkwznyq: + /eslint-module-utils/2.7.3_vcyzkqbdgh7pbhuc7ez2cv5xqa: resolution: {integrity: sha512-088JEC7O3lDZM9xGe0RerkOMd0EjFl+Yvd1jPWIkMT5u3H9+HC34mWWPnqPrN13gieT9pBOO+Qt07Nb/6TresQ==} engines: {node: '>=4'} peerDependencies: @@ -1671,14 +1722,23 @@ packages: '@typescript-eslint/parser': 5.36.2_wyqvi574yv7oiwfeinomdzmc3m debug: 3.2.7 eslint-import-resolver-node: 0.3.6 - eslint-import-resolver-typescript: 3.5.1_mynvxvmq5qtyojffiqgev4x7mm find-up: 2.1.0 transitivePeerDependencies: - supports-color dev: true - /eslint-plugin-es/3.0.1_eslint@8.26.0: - resolution: {integrity: sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==} + /eslint-plugin-antfu/0.27.0_wyqvi574yv7oiwfeinomdzmc3m: + resolution: {integrity: sha512-xjNfATHonE3Do2igOlhwjfL2tlaGnm1EgbsLLkHgdk30oIvJU4bLNxF6wXIuaCdjqmwWIqF6smJbX2YhtaEC4w==} + dependencies: + '@typescript-eslint/utils': 5.36.2_wyqvi574yv7oiwfeinomdzmc3m + transitivePeerDependencies: + - eslint + - supports-color + - typescript + dev: true + + /eslint-plugin-es/4.1.0_eslint@8.26.0: + resolution: {integrity: sha512-GILhQTnjYE2WorX5Jyi5i4dz5ALWxBIdQECVQavL6s7cI76IZTDWleTHkxz/QT3kvcs2QlGHvKLYsSlPOlPXnQ==} engines: {node: '>=8.10.0'} peerDependencies: eslint: '>=4.19.1' @@ -1688,18 +1748,24 @@ packages: regexpp: 3.2.0 dev: true - /eslint-plugin-es/4.1.0_eslint@8.26.0: - resolution: {integrity: sha512-GILhQTnjYE2WorX5Jyi5i4dz5ALWxBIdQECVQavL6s7cI76IZTDWleTHkxz/QT3kvcs2QlGHvKLYsSlPOlPXnQ==} - engines: {node: '>=8.10.0'} + /eslint-plugin-eslint-comments/3.2.0_eslint@8.26.0: + resolution: {integrity: sha512-0jkOl0hfojIHHmEHgmNdqv4fmh7300NdpA9FFpF7zaoLvB/QeXOGNLIo86oAveJFrfB1p05kC8hpEMHM8DwWVQ==} + engines: {node: '>=6.5.0'} peerDependencies: eslint: '>=4.19.1' dependencies: + escape-string-regexp: 1.0.5 eslint: 8.26.0 - eslint-utils: 2.1.0 - regexpp: 3.2.0 + ignore: 5.2.0 + dev: true + + /eslint-plugin-html/7.1.0: + resolution: {integrity: sha512-fNLRraV/e6j8e3XYOC9xgND4j+U7b1Rq+OygMlLcMg+wI/IpVbF+ubQa3R78EjKB9njT6TQOlcK5rFKBVVtdfg==} + dependencies: + htmlparser2: 8.0.1 dev: true - /eslint-plugin-import/2.26.0_3kfy4n2yrit4yqblnsz4zmqkii: + /eslint-plugin-import/2.26.0_r2qesmvbtasnioxvcewzbti7fm: resolution: {integrity: sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==} engines: {node: '>=4'} peerDependencies: @@ -1716,7 +1782,7 @@ packages: doctrine: 2.1.0 eslint: 8.26.0 eslint-import-resolver-node: 0.3.6 - eslint-module-utils: 2.7.3_7liths4w263er5tix7tpkwznyq + eslint-module-utils: 2.7.3_vcyzkqbdgh7pbhuc7ez2cv5xqa has: 1.0.3 is-core-module: 2.10.0 is-glob: 4.0.3 @@ -1730,6 +1796,30 @@ packages: - supports-color dev: true + /eslint-plugin-jsonc/2.5.0_eslint@8.26.0: + resolution: {integrity: sha512-G257khwkrOQ5MJpSzz4yQh5K12W4xFZRcHmVlhVFWh2GCLDX+JwHnmkQoUoFDbOieSPBMsPFZDTJScwrXiWlIg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: '>=6.0.0' + dependencies: + eslint: 8.26.0 + eslint-utils: 3.0.0_eslint@8.26.0 + jsonc-eslint-parser: 2.1.0 + natural-compare: 1.4.0 + dev: true + + /eslint-plugin-markdown/3.0.0_eslint@8.26.0: + resolution: {integrity: sha512-hRs5RUJGbeHDLfS7ELanT0e29Ocyssf/7kBM+p7KluY5AwngGkDf8Oyu4658/NZSGTTq05FZeWbkxXtbVyHPwg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || ^8.0.0 + dependencies: + eslint: 8.26.0 + mdast-util-from-markdown: 0.8.5 + transitivePeerDependencies: + - supports-color + dev: true + /eslint-plugin-n/15.2.5_eslint@8.26.0: resolution: {integrity: sha512-8+BYsqiyZfpu6NXmdLOXVUfk8IocpCjpd8nMRRH0A9ulrcemhb2VI9RSJMEy5udx++A/YcVPD11zT8hpFq368g==} engines: {node: '>=12.22.0'} @@ -1747,21 +1837,6 @@ packages: semver: 7.3.7 dev: true - /eslint-plugin-node/11.1.0_eslint@8.26.0: - resolution: {integrity: sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==} - engines: {node: '>=8.10.0'} - peerDependencies: - eslint: '>=5.16.0' - dependencies: - eslint: 8.26.0 - eslint-plugin-es: 3.0.1_eslint@8.26.0 - eslint-utils: 2.1.0 - ignore: 5.2.0 - minimatch: 3.1.2 - resolve: 1.22.1 - semver: 6.3.0 - dev: true - /eslint-plugin-promise/6.0.1_eslint@8.26.0: resolution: {integrity: sha512-uM4Tgo5u3UWQiroOyDEsYcVMOo7re3zmno0IZmB5auxoaQNIceAbXEkSt8RNrKtaYehARHG06pYK6K1JhtP0Zw==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -1812,6 +1887,21 @@ packages: - supports-color dev: true + /eslint-plugin-yml/1.2.0_eslint@8.26.0: + resolution: {integrity: sha512-v0jAU/F5SJg28zkpxwGpY04eGZMWFP6os8u2qaEAIRjSH2GqrNl0yBR5+sMHLU/026kAduxVbvLSqmT3Mu3O0g==} + engines: {node: ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: '>=6.0.0' + dependencies: + debug: 4.3.4 + eslint: 8.26.0 + lodash: 4.17.21 + natural-compare: 1.4.0 + yaml-eslint-parser: 1.1.0 + transitivePeerDependencies: + - supports-color + dev: true + /eslint-scope/5.1.1: resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==} engines: {node: '>=8.0.0'} @@ -2116,10 +2206,6 @@ packages: get-intrinsic: 1.1.1 dev: true - /get-tsconfig/4.2.0: - resolution: {integrity: sha512-X8u8fREiYOE6S8hLbq99PeykTDoLVnxvF4DjWKJmz9xy2nNRdUcV8ZN9tniJFeKyTU3qnC9lL8n4Chd6LmVKHg==} - dev: true - /git-raw-commits/2.0.10: resolution: {integrity: sha512-sHhX5lsbG9SOO6yXdlwgEMQ/ljIn7qMpAbJZCGfXX2fq5T8M5SrDnpYk9/4HswTildcIqatsWa91vty6VhWSaQ==} engines: {node: '>=10'} @@ -2201,10 +2287,6 @@ packages: type-fest: 0.20.2 dev: true - /globalyzer/0.1.0: - resolution: {integrity: sha512-40oNTM9UfG6aBmuKxk/giHn5nQ8RVz/SS4Ir6zgzOv9/qC3kKZ9v4etGTcJbEl/NyVQH7FGU7d+X1egr57Md2Q==} - dev: true - /globby/11.1.0: resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} engines: {node: '>=10'} @@ -2217,21 +2299,6 @@ packages: slash: 3.0.0 dev: true - /globby/13.1.2: - resolution: {integrity: sha512-LKSDZXToac40u8Q1PQtZihbNdTYSNMuWe+K5l+oa6KgDzSvVrHXlJy40hUP522RjAIoNLJYBJi7ow+rbFpIhHQ==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - dependencies: - dir-glob: 3.0.1 - fast-glob: 3.2.12 - ignore: 5.2.0 - merge2: 1.4.1 - slash: 4.0.0 - dev: true - - /globrex/0.1.2: - resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==} - dev: true - /graceful-fs/4.2.9: resolution: {integrity: sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==} dev: true @@ -2302,6 +2369,15 @@ packages: lru-cache: 6.0.0 dev: true + /htmlparser2/8.0.1: + resolution: {integrity: sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==} + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + domutils: 3.0.1 + entities: 4.4.0 + dev: true + /human-signals/2.1.0: resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} engines: {node: '>=10.17.0'} @@ -2382,6 +2458,17 @@ packages: engines: {node: '>= 0.10'} dev: true + /is-alphabetical/1.0.4: + resolution: {integrity: sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg==} + dev: true + + /is-alphanumerical/1.0.4: + resolution: {integrity: sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A==} + dependencies: + is-alphabetical: 1.0.4 + is-decimal: 1.0.4 + dev: true + /is-arrayish/0.2.1: resolution: {integrity: sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=} dev: true @@ -2431,10 +2518,8 @@ packages: has-tostringtag: 1.0.0 dev: true - /is-docker/2.2.1: - resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==} - engines: {node: '>=8'} - hasBin: true + /is-decimal/1.0.4: + resolution: {integrity: sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw==} dev: true /is-extglob/2.1.1: @@ -2452,6 +2537,10 @@ packages: dependencies: is-extglob: 2.1.1 + /is-hexadecimal/1.0.4: + resolution: {integrity: sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw==} + dev: true + /is-negative-zero/2.0.2: resolution: {integrity: sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==} engines: {node: '>= 0.4'} @@ -2534,13 +2623,6 @@ packages: call-bind: 1.0.2 dev: true - /is-wsl/2.2.0: - resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==} - engines: {node: '>=8'} - dependencies: - is-docker: 2.2.1 - dev: true - /isarray/1.0.0: resolution: {integrity: sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=} dev: true @@ -2615,6 +2697,16 @@ packages: minimist: 1.2.6 dev: true + /jsonc-eslint-parser/2.1.0: + resolution: {integrity: sha512-qCRJWlbP2v6HbmKW7R3lFbeiVWHo+oMJ0j+MizwvauqnCV/EvtAeEeuCgoc/ErtsuoKgYB8U4Ih8AxJbXoE6/g==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + dependencies: + acorn: 8.8.1 + eslint-visitor-keys: 3.3.0 + espree: 9.4.0 + semver: 7.3.7 + dev: true + /jsonfile/6.1.0: resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==} dependencies: @@ -2753,6 +2845,22 @@ packages: engines: {node: '>=8'} dev: true + /mdast-util-from-markdown/0.8.5: + resolution: {integrity: sha512-2hkTXtYYnr+NubD/g6KGBS/0mFmBcifAsI0yIWRiRo0PjVs6SSOSOdtzbp6kSGnShDN6G5aWZpKQ2lWRy27mWQ==} + dependencies: + '@types/mdast': 3.0.10 + mdast-util-to-string: 2.0.0 + micromark: 2.11.4 + parse-entities: 2.0.0 + unist-util-stringify-position: 2.0.3 + transitivePeerDependencies: + - supports-color + dev: true + + /mdast-util-to-string/2.0.0: + resolution: {integrity: sha512-AW4DRS3QbBayY/jJmD8437V1Gombjf8RSOUCMFBuo5iHi58AGEgVCKQ+ezHkZZDpAQS75hcBMpLqjpJTjtUL7w==} + dev: true + /meow/8.1.2: resolution: {integrity: sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q==} engines: {node: '>=10'} @@ -2779,6 +2887,15 @@ packages: engines: {node: '>= 8'} dev: true + /micromark/2.11.4: + resolution: {integrity: sha512-+WoovN/ppKolQOFIAajxi7Lu9kInbPxFuTBVEavFcL8eAfVstoc5MocPmqBeAdBOJV00uaVjegzH4+MA0DN/uA==} + dependencies: + debug: 4.3.4 + parse-entities: 2.0.0 + transitivePeerDependencies: + - supports-color + dev: true + /micromatch/4.0.4: resolution: {integrity: sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==} engines: {node: '>=8.6'} @@ -2957,15 +3074,6 @@ packages: mimic-fn: 2.1.0 dev: true - /open/8.4.0: - resolution: {integrity: sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==} - engines: {node: '>=12'} - dependencies: - define-lazy-prop: 2.0.0 - is-docker: 2.2.1 - is-wsl: 2.2.0 - dev: true - /optionator/0.9.1: resolution: {integrity: sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==} engines: {node: '>= 0.8.0'} @@ -3037,6 +3145,17 @@ packages: callsites: 3.1.0 dev: true + /parse-entities/2.0.0: + resolution: {integrity: sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ==} + dependencies: + character-entities: 1.2.4 + character-entities-legacy: 1.1.4 + character-reference-invalid: 1.1.4 + is-alphanumerical: 1.0.4 + is-decimal: 1.0.4 + is-hexadecimal: 1.0.4 + dev: true + /parse-json/4.0.0: resolution: {integrity: sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=} engines: {node: '>=4'} @@ -3459,11 +3578,6 @@ packages: engines: {node: '>=8'} dev: true - /slash/4.0.0: - resolution: {integrity: sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==} - engines: {node: '>=12'} - dev: true - /source-map-js/1.0.2: resolution: {integrity: sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==} engines: {node: '>=0.10.0'} @@ -3645,14 +3759,6 @@ packages: engines: {node: '>= 0.4'} dev: true - /synckit/0.8.4: - resolution: {integrity: sha512-Dn2ZkzMdSX827QbowGbU/4yjWuvNaCoScLLoMo/yKbu+P4GBR6cRGKZH27k6a9bRzdqcyd1DE96pQtQ6uNkmyw==} - engines: {node: ^14.18.0 || >=16.0.0} - dependencies: - '@pkgr/utils': 2.3.1 - tslib: 2.4.0 - dev: true - /tapable/2.2.1: resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==} engines: {node: '>=6'} @@ -3753,13 +3859,6 @@ packages: readable-stream: 3.6.0 dev: true - /tiny-glob/0.2.9: - resolution: {integrity: sha512-g/55ssRPUjShh+xkfx9UPDXqhckHEsHr4Vd9zX55oSdGZc/MD0m3sferOkwWtp98bv+kcVfEHtRJgBVJzelrzg==} - dependencies: - globalyzer: 0.1.0 - globrex: 0.1.2 - dev: true - /tinybench/2.3.0: resolution: {integrity: sha512-zs1gMVBwyyG2QbVchYIbnabRhMOCGvrwZz/q+SV+LIMa9q5YDQZi2kkI6ZRqV2Bz7ba1uvrc7ieUoE4KWnGeKg==} dev: true @@ -3813,10 +3912,6 @@ packages: resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==} dev: true - /tslib/2.4.0: - resolution: {integrity: sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==} - dev: true - /tsup/6.3.0_typescript@4.8.4: resolution: {integrity: sha512-IaNQO/o1rFgadLhNonVKNCT2cks+vvnWX3DnL8sB87lBDqRvJXHENr5lSPJlqwplUlDxSwZK8dSg87rgBu6Emw==} engines: {node: '>=14'} @@ -3918,6 +4013,12 @@ packages: which-boxed-primitive: 1.0.2 dev: true + /unist-util-stringify-position/2.0.3: + resolution: {integrity: sha512-3faScn5I+hy9VleOq/qNbAd6pAx7iH5jYBMS9I1HgQVijz/4mv5Bvw5iw1sC/90CODiKo81G/ps8AJrISn687g==} + dependencies: + '@types/unist': 2.0.6 + dev: true + /universalify/2.0.0: resolution: {integrity: sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==} engines: {node: '>= 10.0.0'} @@ -4207,11 +4308,25 @@ packages: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} dev: true + /yaml-eslint-parser/1.1.0: + resolution: {integrity: sha512-b464Q1fYiX1oYx2kE8k4mEp6S9Prk+tfDsY/IPxQ0FCjEuj3AKko5Skf3/yQJeYTTDyjDE+aWIJemnv29HvEWQ==} + engines: {node: ^14.17.0 || >=16.0.0} + dependencies: + eslint-visitor-keys: 3.3.0 + lodash: 4.17.21 + yaml: 2.1.3 + dev: true + /yaml/1.10.2: resolution: {integrity: sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==} engines: {node: '>= 6'} dev: true + /yaml/2.1.3: + resolution: {integrity: sha512-AacA8nRULjKMX2DvWvOAdBZMOfQlypSFkjcOcu9FalllIDJ1kvlREzcdIZmidQUqqeMv7jorHjq2HlLv/+c2lg==} + engines: {node: '>= 14'} + dev: true + /yargs-parser/20.2.9: resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} engines: {node: '>=10'} diff --git a/scripts/buildFixtures.ts b/scripts/buildFixtures.ts index 57553f85..ce00b7a7 100644 --- a/scripts/buildFixtures.ts +++ b/scripts/buildFixtures.ts @@ -1,22 +1,20 @@ -/* eslint-disable no-console */ -import { resolve, join } from 'path' +import { join, resolve } from 'path' import { execSync } from 'child_process' import fs from 'fs-extra' import c from 'picocolors' -async function run () { +async function run() { const dir = resolve(__dirname, '../test/fixtures') let fixtures = await fs.readdir(dir) - if (process.argv[2]) { + if (process.argv[2]) fixtures = fixtures.filter(i => i.includes(process.argv[2])) - } for (const name of fixtures) { const path = join(dir, name) - if (fs.existsSync(join(path, 'dist'))) { + if (fs.existsSync(join(path, 'dist'))) await fs.remove(join(path, 'dist')) - } + console.log(c.yellow(c.inverse(c.bold('\n Vite '))), name, '\n') execSync('npx vite --version', { cwd: path, stdio: 'inherit' }) execSync('npx vite build', { cwd: path, stdio: 'inherit' }) diff --git a/src/define.ts b/src/define.ts index f90cc0f0..a5b0ccb7 100644 --- a/src/define.ts +++ b/src/define.ts @@ -1,34 +1,33 @@ -/* eslint-disable no-redeclare */ import { getEsbuildPlugin } from './esbuild' import { getRollupPlugin } from './rollup' -import { UnpluginInstance, UnpluginFactory } from './types' +import type { UnpluginFactory, UnpluginInstance } from './types' import { getVitePlugin } from './vite' import { getWebpackPlugin } from './webpack' -export function createUnplugin ( +export function createUnplugin( factory: UnpluginFactory ): UnpluginInstance -export function createUnplugin ( +export function createUnplugin( factory: UnpluginFactory ): UnpluginInstance -export function createUnplugin ( - factory: UnpluginFactory +export function createUnplugin( + factory: UnpluginFactory, ): UnpluginInstance { return { - get esbuild () { + get esbuild() { return getEsbuildPlugin(factory) }, - get rollup () { + get rollup() { return getRollupPlugin(factory) }, - get vite () { + get vite() { return getVitePlugin(factory) }, - get webpack () { + get webpack() { return getWebpackPlugin(factory) }, - get raw () { + get raw() { return factory - } + }, } } diff --git a/src/esbuild/index.ts b/src/esbuild/index.ts index 5feb962f..48342b03 100644 --- a/src/esbuild/index.ts +++ b/src/esbuild/index.ts @@ -4,76 +4,71 @@ import chokidar from 'chokidar' import type { PartialMessage } from 'esbuild' import type { SourceMap } from 'rollup' import { Parser } from 'acorn' -import { RawSourceMap } from '@ampproject/remapping' +import type { RawSourceMap } from '@ampproject/remapping' import type { EsbuildPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginInstance, UnpluginOptions } from '../types' -import { toArray, combineSourcemaps, fixSourceMap, guessLoader } from './utils' +import { combineSourcemaps, fixSourceMap, guessLoader, toArray } from './utils' const watchListRecord: Record = {} const watchList: Set = new Set() let i = 0 -export function getEsbuildPlugin ( - factory: UnpluginFactory +export function getEsbuildPlugin ( + factory: UnpluginFactory, ): UnpluginInstance['esbuild'] { return (userOptions?: UserOptions): EsbuildPlugin => { const meta: UnpluginContextMeta = { - framework: 'esbuild' + framework: 'esbuild', } const plugins = toArray(factory(userOptions!, meta)) const setup = (plugin: UnpluginOptions): EsbuildPlugin['setup'] => - plugin.esbuild?.setup ?? - (({ onStart, onEnd, onResolve, onLoad, initialOptions, esbuild: { build } }) => { + plugin.esbuild?.setup + ?? (({ onStart, onEnd, onResolve, onLoad, initialOptions, esbuild: { build } }) => { const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/ const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/ const context: UnpluginBuildContext = { - parse (code: string, opts: any = {}) { + parse(code: string, opts: any = {}) { return Parser.parse(code, { sourceType: 'module', ecmaVersion: 'latest', locations: true, - ...opts + ...opts, }) }, - addWatchFile (id) { + addWatchFile(id) { watchList.add(path.resolve(id)) }, - emitFile (emittedFile) { + emitFile(emittedFile) { const outFileName = emittedFile.fileName || emittedFile.name - if (initialOptions.outdir && emittedFile.source && outFileName) { + if (initialOptions.outdir && emittedFile.source && outFileName) fs.writeFileSync(path.resolve(initialOptions.outdir, outFileName), emittedFile.source) - } }, - getWatchFiles () { + getWatchFiles() { return Array.from(watchList) - } + }, } // Ensure output directory exists for this.emitFile - if (initialOptions.outdir && !fs.existsSync(initialOptions.outdir)) { + if (initialOptions.outdir && !fs.existsSync(initialOptions.outdir)) fs.mkdirSync(initialOptions.outdir, { recursive: true }) - } - if (plugin.buildStart) { + if (plugin.buildStart) onStart(() => plugin.buildStart!.call(context)) - } if (plugin.buildEnd || plugin.writeBundle || initialOptions.watch) { const rebuild = () => build({ ...initialOptions, - watch: false + watch: false, }) onEnd(async () => { - if (plugin.buildEnd) { + if (plugin.buildEnd) await plugin.buildEnd.call(context) - } - if (plugin.writeBundle) { + if (plugin.writeBundle) await plugin.writeBundle() - } if (initialOptions.watch) { Object.keys(watchListRecord).forEach((id) => { @@ -113,13 +108,12 @@ export function getEsbuildPlugin ( // We explicitly have this if statement here for consistency with the integration of other bundelers. // Here, `args.importer` is just an empty string on entry files whereas the euqivalent on other bundlers is `undefined.` isEntry ? undefined : args.importer, - { isEntry } + { isEntry }, ) - if (typeof result === 'string') { + if (typeof result === 'string') return { path: result, namespace: plugin.name } - } else if (typeof result === 'object' && result !== null) { + else if (typeof result === 'object' && result !== null) return { path: result.id, external: result.external, namespace: plugin.name } - } }) } @@ -130,8 +124,8 @@ export function getEsbuildPlugin ( const errors: PartialMessage[] = [] const warnings: PartialMessage[] = [] const pluginContext: UnpluginContext = { - error (message) { errors.push({ text: String(message) }) }, - warn (message) { warnings.push({ text: String(message) }) } + error(message) { errors.push({ text: String(message) }) }, + warn(message) { warnings.push({ text: String(message) }) }, } // because we use `namespace` to simulate virtual modules, // it is required to forward `resolveDir` for esbuild to find dependencies. @@ -143,21 +137,22 @@ export function getEsbuildPlugin ( const result = await plugin.load.call(Object.assign(context, pluginContext), id) if (typeof result === 'string') { code = result - } else if (typeof result === 'object' && result !== null) { + } + else if (typeof result === 'object' && result !== null) { code = result.code map = result.map as any } } if (!plugin.transform) { - if (code === undefined) { + if (code === undefined) return null - } + if (map) { // fix missing sourcesContent, esbuild depends on it - if (!map.sourcesContent || map.sourcesContent.length === 0) { + if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code] - } + map = fixSourceMap(map as RawSourceMap) code += `\n//# sourceMappingURL=${map.toUrl()}` } @@ -175,16 +170,18 @@ export function getEsbuildPlugin ( const result = await plugin.transform.call(Object.assign(context, pluginContext), code, id) if (typeof result === 'string') { code = result - } else if (typeof result === 'object' && result !== null) { + } + else if (typeof result === 'object' && result !== null) { code = result.code // if we already got sourcemap from `load()`, // combine the two sourcemaps if (map && result.map) { map = combineSourcemaps(args.path, [ - result.map as RawSourceMap, - map as RawSourceMap + result.map as RawSourceMap, + map as RawSourceMap, ]) as SourceMap - } else { + } + else { // otherwise, we always keep the last one, even if it's empty map = result.map as any } @@ -193,9 +190,9 @@ export function getEsbuildPlugin ( if (code) { if (map) { - if (!map.sourcesContent || map.sourcesContent.length === 0) { + if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code] - } + map = fixSourceMap(map as RawSourceMap) code += `\n//# sourceMappingURL=${map.toUrl()}` } @@ -205,11 +202,10 @@ export function getEsbuildPlugin ( } }) - const setupMultiplePlugins = ():EsbuildPlugin['setup'] => + const setupMultiplePlugins = (): EsbuildPlugin['setup'] => (build) => { - for (const plugin of plugins) { + for (const plugin of plugins) setup(plugin)(build) - } } return plugins.length === 1 diff --git a/src/esbuild/utils.ts b/src/esbuild/utils.ts index c146218b..3d8fd721 100644 --- a/src/esbuild/utils.ts +++ b/src/esbuild/utils.ts @@ -2,7 +2,7 @@ import { extname } from 'path' import remapping from '@ampproject/remapping' import type { DecodedSourceMap, - RawSourceMap + RawSourceMap, } from '@ampproject/remapping/dist/types/types' import type { Loader } from 'esbuild' import type { SourceMap } from 'rollup' @@ -24,30 +24,30 @@ const ExtToLoader: Record = { '.scss': 'css', '.sass': 'css', '.json': 'json', - '.txt': 'text' + '.txt': 'text', } -export function guessLoader (id: string): Loader { +export function guessLoader(id: string): Loader { return ExtToLoader[extname(id).toLowerCase()] || 'js' } // `load` and `transform` may return a sourcemap without toString and toUrl, // but esbuild needs them, we fix the two methods -export function fixSourceMap (map: RawSourceMap): SourceMap { +export function fixSourceMap(map: RawSourceMap): SourceMap { if (!('toString' in map)) { Object.defineProperty(map, 'toString', { enumerable: false, - value: function toString () { + value: function toString() { return JSON.stringify(this) - } + }, }) } if (!('toUrl' in map)) { Object.defineProperty(map, 'toUrl', { enumerable: false, - value: function toUrl () { - return 'data:application/json;charset=utf-8;base64,' + Buffer.from(this.toString()).toString('base64') - } + value: function toUrl() { + return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString('base64')}` + }, }) } return map as SourceMap @@ -58,44 +58,42 @@ const nullSourceMap: RawSourceMap = { names: [], sources: [], mappings: '', - version: 3 + version: 3, } -export function combineSourcemaps ( +export function combineSourcemaps( filename: string, - sourcemapList: Array + sourcemapList: Array, ): RawSourceMap { sourcemapList = sourcemapList.filter(m => m.sources) if ( - sourcemapList.length === 0 || - sourcemapList.every(m => m.sources.length === 0) - ) { + sourcemapList.length === 0 + || sourcemapList.every(m => m.sources.length === 0) + ) return { ...nullSourceMap } - } // We don't declare type here so we can convert/fake/map as RawSourceMap let map // : SourceMap let mapIndex = 1 - const useArrayInterface = - sourcemapList.slice(0, -1).find(m => m.sources.length !== 1) === undefined + const useArrayInterface + = sourcemapList.slice(0, -1).find(m => m.sources.length !== 1) === undefined if (useArrayInterface) { map = remapping(sourcemapList, () => null, true) - } else { + } + else { map = remapping( sourcemapList[0], - function loader (sourcefile) { - if (sourcefile === filename && sourcemapList[mapIndex]) { + (sourcefile) => { + if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++] - } else { + else return { ...nullSourceMap } - } }, - true + true, ) } - if (!map.file) { + if (!map.file) delete map.file - } return map as RawSourceMap } diff --git a/src/rollup/index.ts b/src/rollup/index.ts index feb9db1c..4b6f2024 100644 --- a/src/rollup/index.ts +++ b/src/rollup/index.ts @@ -1,12 +1,12 @@ -import { UnpluginInstance, UnpluginFactory, UnpluginOptions, RollupPlugin, UnpluginContextMeta } from '../types' +import type { RollupPlugin, UnpluginContextMeta, UnpluginFactory, UnpluginInstance, UnpluginOptions } from '../types' import { toArray } from '../utils' -export function getRollupPlugin ( - factory: UnpluginFactory +export function getRollupPlugin ( + factory: UnpluginFactory, ): UnpluginInstance['rollup'] { return (userOptions?: UserOptions) => { const meta: UnpluginContextMeta = { - framework: 'rollup' + framework: 'rollup', } const rawPlugins = toArray(factory(userOptions!, meta)) const plugins = rawPlugins.map(plugin => toRollupPlugin(plugin)) @@ -14,13 +14,13 @@ export function getRollupPlugin ( } } -export function toRollupPlugin (plugin: UnpluginOptions, containRollupOptions = true): RollupPlugin { +export function toRollupPlugin(plugin: UnpluginOptions, containRollupOptions = true): RollupPlugin { if (plugin.transform && plugin.transformInclude) { const _transform = plugin.transform plugin.transform = function (code, id) { - if (plugin.transformInclude && !plugin.transformInclude(id)) { + if (plugin.transformInclude && !plugin.transformInclude(id)) return null - } + return _transform.call(this, code, id) } } @@ -28,16 +28,15 @@ export function toRollupPlugin (plugin: UnpluginOptions, containRollupOptions = if (plugin.load && plugin.loadInclude) { const _load = plugin.load plugin.load = function (id) { - if (plugin.loadInclude && !plugin.loadInclude(id)) { + if (plugin.loadInclude && !plugin.loadInclude(id)) return null - } + return _load.call(this, id) } } - if (plugin.rollup && containRollupOptions) { + if (plugin.rollup && containRollupOptions) Object.assign(plugin, plugin.rollup) - } return plugin } diff --git a/src/types.ts b/src/types.ts index 24b0cf73..2322bac8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,4 @@ -import type { AcornNode, EmittedAsset, Plugin as RollupPlugin, PluginContextMeta as RollupContextMeta, SourceMapInput } from 'rollup' +import type { AcornNode, EmittedAsset, PluginContextMeta as RollupContextMeta, Plugin as RollupPlugin, SourceMapInput } from 'rollup' import type { Compiler as WebpackCompiler, WebpackPluginInstance } from 'webpack' import type { Plugin as VitePlugin } from 'vite' import type { Plugin as EsbuildPlugin } from 'esbuild' @@ -8,30 +8,30 @@ export { EsbuildPlugin, RollupPlugin, VitePlugin, - WebpackCompiler + WebpackCompiler, } export type Thenable = T | Promise -export type TransformResult = string | { code: string; map?: SourceMapInput | null; } | null | undefined +export type TransformResult = string | { code: string; map?: SourceMapInput | null } | null | undefined -export type ExternalIdResult = { id: string, external?: boolean } +export interface ExternalIdResult { id: string; external?: boolean } export interface UnpluginBuildContext { - addWatchFile: (id: string) => void; - emitFile: (emittedFile: EmittedAsset) => void; - getWatchFiles: () => string[]; - parse: (input: string, options?: any) => AcornNode; + addWatchFile: (id: string) => void + emitFile: (emittedFile: EmittedAsset) => void + getWatchFiles: () => string[] + parse: (input: string, options?: any) => AcornNode } export interface UnpluginOptions { - name: string; - enforce?: 'post' | 'pre' | undefined; + name: string + enforce?: 'post' | 'pre' | undefined // Build Hooks - buildStart?: (this: UnpluginBuildContext) => Promise | void; - buildEnd?: (this: UnpluginBuildContext) => Promise | void; - transform?: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable; + buildStart?: (this: UnpluginBuildContext) => Promise | void + buildEnd?: (this: UnpluginBuildContext) => Promise | void + transform?: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable load?: (this: UnpluginBuildContext & UnpluginContext, id: string) => Thenable resolveId?: (id: string, importer: string | undefined, options: { isEntry: boolean }) => Thenable watchChange?: (this: UnpluginBuildContext, id: string, change: { event: 'create' | 'update' | 'delete' }) => void @@ -43,12 +43,12 @@ export interface UnpluginOptions { * Custom predicate function to filter modules to be loaded. * When omitted, all modules will be included (might have potential perf impact on Webpack). */ - loadInclude?: (id: string) => boolean | null | undefined; + loadInclude?: (id: string) => boolean | null | undefined /** * Custom predicate function to filter modules to be transformed. * When omitted, all modules will be included (might have potential perf impact on Webpack). */ - transformInclude?: (id: string) => boolean | null | undefined; + transformInclude?: (id: string) => boolean | null | undefined // framework specify extends rollup?: Partial @@ -70,9 +70,9 @@ export interface ResolvedUnpluginOptions extends UnpluginOptions { } export type UnpluginFactory = (options: UserOptions, meta: UnpluginContextMeta) => - Nested extends true - ? Array - : UnpluginOptions +Nested extends true + ? Array + : UnpluginOptions export type UnpluginFactoryOutput = undefined extends UserOptions ? (options?: UserOptions) => Return : (options: UserOptions) => Return @@ -95,7 +95,7 @@ export type UnpluginContextMeta = Partial & ({ } | { framework: 'esbuild' /** Set the host plugin name of esbuild when returning multiple plugins */ - esbuildHostName?: string, + esbuildHostName?: string }) export interface UnpluginContext { diff --git a/src/utils.ts b/src/utils.ts index 7292343e..86adb6ad 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -10,12 +10,11 @@ import { isAbsolute, normalize } from 'path' * @param path - Path to normalize. * @returns a new normalized path. */ -export function normalizeAbsolutePath (path: string) { - if (isAbsolute(path)) { +export function normalizeAbsolutePath(path: string) { + if (isAbsolute(path)) return normalize(path) - } else { + else return path - } } /** @@ -28,8 +27,9 @@ export type Nullable = T | null | undefined */ export type Arrayable = T | Array -export function toArray (array?: Nullable>): Array { +export function toArray(array?: Nullable>): Array { array = array || [] - if (Array.isArray(array)) { return array } + if (Array.isArray(array)) + return array return [array] } diff --git a/src/vite/index.ts b/src/vite/index.ts index a1f44112..f9eec52f 100644 --- a/src/vite/index.ts +++ b/src/vite/index.ts @@ -1,21 +1,21 @@ import { toRollupPlugin } from '../rollup' -import { UnpluginInstance, UnpluginFactory, VitePlugin, UnpluginContextMeta } from '../types' +import type { UnpluginContextMeta, UnpluginFactory, UnpluginInstance, VitePlugin } from '../types' import { toArray } from '../utils' -export function getVitePlugin ( - factory: UnpluginFactory +export function getVitePlugin ( + factory: UnpluginFactory, ): UnpluginInstance['vite'] { return (userOptions?: UserOptions) => { const meta: UnpluginContextMeta = { - framework: 'vite' + framework: 'vite', } const rawPlugins = toArray(factory(userOptions!, meta)) const plugins = rawPlugins.map((rawPlugin) => { const plugin = toRollupPlugin(rawPlugin, false) as VitePlugin - if (rawPlugin.vite) { + if (rawPlugin.vite) Object.assign(plugin, rawPlugin.vite) - } + return plugin }) diff --git a/src/webpack/context.ts b/src/webpack/context.ts index b12f7b9b..0117060f 100644 --- a/src/webpack/context.ts +++ b/src/webpack/context.ts @@ -1,49 +1,47 @@ import { resolve } from 'path' -// eslint-disable-next-line import/default import sources from 'webpack-sources' import type { Compilation } from 'webpack' import { Parser } from 'acorn' import type { UnpluginBuildContext } from 'src' -export function createContext (compilation: Compilation): UnpluginBuildContext { +export function createContext(compilation: Compilation): UnpluginBuildContext { return { - parse (code: string, opts: any = {}) { + parse(code: string, opts: any = {}) { return Parser.parse(code, { sourceType: 'module', ecmaVersion: 'latest', locations: true, - ...opts + ...opts, }) }, - addWatchFile (id) { + addWatchFile(id) { (compilation.fileDependencies ?? compilation.compilationDependencies).add( - resolve(process.cwd(), id) + resolve(process.cwd(), id), ) }, - emitFile (emittedFile) { + emitFile(emittedFile) { const outFileName = emittedFile.fileName || emittedFile.name if (emittedFile.source && outFileName) { compilation.emitAsset( outFileName, - // @ts-ignore sources ? new sources.RawSource( // @ts-expect-error types mismatch typeof emittedFile.source === 'string' ? emittedFile.source - : Buffer.from(emittedFile.source) - ) + : Buffer.from(emittedFile.source), + ) as any : { source: () => emittedFile.source, - size: () => emittedFile.source!.length - } + size: () => emittedFile.source!.length, + }, ) } }, - getWatchFiles () { + getWatchFiles() { return Array.from( - compilation.fileDependencies ?? compilation.compilationDependencies + compilation.fileDependencies ?? compilation.compilationDependencies, ) - } + }, } } diff --git a/src/webpack/index.ts b/src/webpack/index.ts index b44f3bc7..7fa3e7bc 100644 --- a/src/webpack/index.ts +++ b/src/webpack/index.ts @@ -1,9 +1,9 @@ import fs from 'fs' import { fileURLToPath } from 'url' -import { resolve, dirname } from 'path' +import { dirname, resolve } from 'path' import VirtualModulesPlugin from 'webpack-virtual-modules' import type { ResolvePluginInstance, RuleSetUseItem } from 'webpack' -import type { UnpluginContextMeta, UnpluginInstance, UnpluginFactory, WebpackCompiler, ResolvedUnpluginOptions } from '../types' +import type { ResolvedUnpluginOptions, UnpluginContextMeta, UnpluginFactory, UnpluginInstance, WebpackCompiler } from '../types' import { normalizeAbsolutePath, toArray } from '../utils' import { createContext } from './context' @@ -11,32 +11,32 @@ const _dirname = typeof __dirname !== 'undefined' ? __dirname : dirname(fileURLT const TRANSFORM_LOADER = resolve( _dirname, - __DEV__ ? '../../dist/webpack/loaders/transform' : 'webpack/loaders/transform' + __DEV__ ? '../../dist/webpack/loaders/transform' : 'webpack/loaders/transform', ) const LOAD_LOADER = resolve( _dirname, - __DEV__ ? '../../dist/webpack/loaders/load' : 'webpack/loaders/load' + __DEV__ ? '../../dist/webpack/loaders/load' : 'webpack/loaders/load', ) // We need the prefix of virtual modules to be an absolute path so webpack let's us load them (even if it's made up) // In the loader we strip the made up prefix path again const VIRTUAL_MODULE_PREFIX = resolve(process.cwd(), '_virtual_') -export function getWebpackPlugin ( - factory: UnpluginFactory +export function getWebpackPlugin( + factory: UnpluginFactory, ): UnpluginInstance['webpack'] { return (userOptions?: UserOptions) => { return { - apply (compiler: WebpackCompiler) { + apply(compiler: WebpackCompiler) { const injected = compiler.$unpluginContext || {} compiler.$unpluginContext = injected const meta: UnpluginContextMeta = { framework: 'webpack', webpack: { - compiler - } + compiler, + }, } const rawPlugins = toArray(factory(userOptions!, meta)) @@ -45,8 +45,8 @@ export function getWebpackPlugin ( rawPlugin, { __unpluginMeta: meta, - __virtualModulePrefix: VIRTUAL_MODULE_PREFIX - } + __virtualModulePrefix: VIRTUAL_MODULE_PREFIX, + }, ) as ResolvedUnpluginOptions // inject context object to share with loaders @@ -63,21 +63,21 @@ export function getWebpackPlugin ( // transform hook if (plugin.transform) { const useLoader: RuleSetUseItem[] = [{ - loader: `${TRANSFORM_LOADER}?unpluginName=${encodeURIComponent(plugin.name)}` + loader: `${TRANSFORM_LOADER}?unpluginName=${encodeURIComponent(plugin.name)}`, }] const useNone: RuleSetUseItem[] = [] compiler.options.module.rules.unshift({ enforce: plugin.enforce, - use: (data: { resource: string | null, resourceQuery: string }) => { - if (data.resource == null) { + use: (data: { resource: string | null; resourceQuery: string }) => { + if (data.resource == null) return useNone - } + const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || '')) - if (!plugin.transformInclude || plugin.transformInclude(id)) { + if (!plugin.transformInclude || plugin.transformInclude(id)) return useLoader - } + return useNone - } + }, }) } @@ -92,20 +92,18 @@ export function getWebpackPlugin ( plugin.__vfs = vfs const resolverPlugin: ResolvePluginInstance = { - apply (resolver) { + apply(resolver) { const target = resolver.ensureHook('resolve') resolver .getHook('resolve') .tapAsync(plugin.name, async (request, resolveContext, callback) => { - if (!request.request) { + if (!request.request) return callback() - } // filter out invalid requests - if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) { + if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback() - } const id = normalizeAbsolutePath(request.request) @@ -116,23 +114,21 @@ export function getWebpackPlugin ( // call hook const resolveIdResult = await plugin.resolveId!(id, importer, { isEntry }) - if (resolveIdResult == null) { + if (resolveIdResult == null) return callback() - } let resolved = typeof resolveIdResult === 'string' ? resolveIdResult : resolveIdResult.id const isExternal = typeof resolveIdResult === 'string' ? false : resolveIdResult.external === true - if (isExternal) { + if (isExternal) externalModules.add(resolved) - } // If the resolved module does not exist, // we treat it as a virtual module if (!fs.existsSync(resolved)) { resolved = normalizeAbsolutePath( - plugin.__virtualModulePrefix + - encodeURIComponent(resolved) // URI encode id so webpack doesn't think it's part of the path + plugin.__virtualModulePrefix + + encodeURIComponent(resolved), // URI encode id so webpack doesn't think it's part of the path ) // webpack virtual module should pass in the correct path @@ -146,13 +142,13 @@ export function getWebpackPlugin ( // construct the new request const newRequest = { ...request, - request: resolved + request: resolved, } // redirect the resolver resolver.doResolve(target, newRequest, null, resolveContext, callback) }) - } + }, } compiler.options.resolve.plugins = compiler.options.resolve.plugins || [] @@ -162,15 +158,13 @@ export function getWebpackPlugin ( // load hook if (plugin.load) { compiler.options.module.rules.unshift({ - include (id) { - if (id.startsWith(plugin.__virtualModulePrefix)) { + include(id) { + if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)) - } // load include filter - if (plugin.loadInclude && !plugin.loadInclude(id)) { + if (plugin.loadInclude && !plugin.loadInclude(id)) return false - } // Don't run load hook for external modules return !externalModules.has(id) @@ -179,37 +173,35 @@ export function getWebpackPlugin ( use: [{ loader: LOAD_LOADER, options: { - unpluginName: plugin.name - } - }] + unpluginName: plugin.name, + }, + }], }) } - if (plugin.webpack) { + if (plugin.webpack) plugin.webpack(compiler) - } if (plugin.watchChange || plugin.buildStart) { compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { const context = createContext(compilation) if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { - const promises:Promise[] = [] + const promises: Promise[] = [] if (compiler.modifiedFiles) { compiler.modifiedFiles.forEach(file => - promises.push(Promise.resolve(plugin.watchChange!.call(context, file, { event: 'update' }))) + promises.push(Promise.resolve(plugin.watchChange!.call(context, file, { event: 'update' }))), ) } if (compiler.removedFiles) { compiler.removedFiles.forEach(file => - promises.push(Promise.resolve(plugin.watchChange!.call(context, file, { event: 'delete' }))) + promises.push(Promise.resolve(plugin.watchChange!.call(context, file, { event: 'delete' }))), ) } await Promise.all(promises) } - if (plugin.buildStart) { + if (plugin.buildStart) return await plugin.buildStart.call(context) - } }) } @@ -225,7 +217,7 @@ export function getWebpackPlugin ( }) } } - } + }, } } } diff --git a/src/webpack/loaders/load.ts b/src/webpack/loaders/load.ts index 1c7c967a..da8b7410 100644 --- a/src/webpack/loaders/load.ts +++ b/src/webpack/loaders/load.ts @@ -1,37 +1,34 @@ import type { LoaderContext } from 'webpack' -import { UnpluginContext } from '../../types' +import type { UnpluginContext } from '../../types' import { createContext } from '../context' import { normalizeAbsolutePath } from '../../utils' -export default async function load (this: LoaderContext, source: string, map: any) { +export default async function load(this: LoaderContext, source: string, map: any) { const callback = this.async() const { unpluginName } = this.query const plugin = this._compiler?.$unpluginContext[unpluginName] let id = this.resource - if (!plugin?.load || !id) { + if (!plugin?.load || !id) return callback(null, source, map) - } const context: UnpluginContext = { error: error => this.emitError(typeof error === 'string' ? new Error(error) : error), - warn: error => this.emitWarning(typeof error === 'string' ? new Error(error) : error) + warn: error => this.emitWarning(typeof error === 'string' ? new Error(error) : error), } - if (id.startsWith(plugin.__virtualModulePrefix)) { + if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)) - } const res = await plugin.load.call( Object.assign(this._compilation && createContext(this._compilation) as any, context), - normalizeAbsolutePath(id) + normalizeAbsolutePath(id), ) - if (res == null) { + if (res == null) callback(null, source, map) - } else if (typeof res !== 'string') { + else if (typeof res !== 'string') callback(null, res.code, res.map ?? map) - } else { + else callback(null, res, map) - } } diff --git a/src/webpack/loaders/transform.ts b/src/webpack/loaders/transform.ts index bb773ce3..9278bbde 100644 --- a/src/webpack/loaders/transform.ts +++ b/src/webpack/loaders/transform.ts @@ -1,35 +1,34 @@ import type { LoaderContext } from 'webpack' -import { UnpluginContext } from '../../types' +import type { UnpluginContext } from '../../types' import { createContext } from '../context' -export default async function transform (this: LoaderContext, source: string, map: any) { +export default async function transform(this: LoaderContext, source: string, map: any) { const callback = this.async() let unpluginName if (typeof this.query === 'string') { const query = new URLSearchParams(this.query) unpluginName = query.get('unpluginName') - } else { + } + else { unpluginName = this.query.unpluginName } const plugin = this._compiler?.$unpluginContext[unpluginName] - if (!plugin?.transform) { + if (!plugin?.transform) return callback(null, source, map) - } const context: UnpluginContext = { error: error => this.emitError(typeof error === 'string' ? new Error(error) : error), - warn: error => this.emitWarning(typeof error === 'string' ? new Error(error) : error) + warn: error => this.emitWarning(typeof error === 'string' ? new Error(error) : error), } const res = await plugin.transform.call(Object.assign(this._compilation && createContext(this._compilation) as any, context), source, this.resource) - if (res == null) { + if (res == null) callback(null, source, map) - } else if (typeof res !== 'string') { + else if (typeof res !== 'string') callback(null, res.code, map == null ? map : (res.map || map)) - } else { + else callback(null, res, map) - } } diff --git a/test/fixtures/transform/__test__/build.test.ts b/test/fixtures/transform/__test__/build.test.ts index ac2cb0ad..21c57f3e 100644 --- a/test/fixtures/transform/__test__/build.test.ts +++ b/test/fixtures/transform/__test__/build.test.ts @@ -1,6 +1,6 @@ import { resolve } from 'path' import fs from 'fs-extra' -import { describe, it, expect } from 'vitest' +import { describe, expect, it } from 'vitest' const r = (...args: string[]) => resolve(__dirname, '../dist', ...args) diff --git a/test/fixtures/virtual-module/__test__/build.test.ts b/test/fixtures/virtual-module/__test__/build.test.ts index 9781f720..3e0d2774 100644 --- a/test/fixtures/virtual-module/__test__/build.test.ts +++ b/test/fixtures/virtual-module/__test__/build.test.ts @@ -1,6 +1,6 @@ import { resolve } from 'path' import fs from 'fs-extra' -import { describe, it, expect } from 'vitest' +import { describe, expect, it } from 'vitest' const r = (...args: string[]) => resolve(__dirname, '../dist', ...args) diff --git a/test/unit-tests/id-consistency/id-consistency.test.ts b/test/unit-tests/id-consistency/id-consistency.test.ts index 74ca0760..154d0e63 100644 --- a/test/unit-tests/id-consistency/id-consistency.test.ts +++ b/test/unit-tests/id-consistency/id-consistency.test.ts @@ -1,32 +1,34 @@ import * as path from 'path' -import { it, describe, expect, vi, afterEach, Mock } from 'vitest' +import type { Mock } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { UnpluginOptions, VitePlugin } from 'unplugin' +import { createUnplugin } from 'unplugin' import { build, toArray } from '../utils' -import { createUnplugin, UnpluginOptions, VitePlugin } from 'unplugin' const entryFilePath = path.resolve(__dirname, './test-src/entry.js') const externals = ['path'] -function createUnpluginWithCallback ( +function createUnpluginWithCallback( resolveIdCallback: UnpluginOptions['resolveId'], transformIncludeCallback: UnpluginOptions['transformInclude'], transformCallback: UnpluginOptions['transform'], - loadCallback: UnpluginOptions['load'] + loadCallback: UnpluginOptions['load'], ) { return createUnplugin(() => ({ name: 'test-plugin', resolveId: resolveIdCallback, transformInclude: transformIncludeCallback, transform: transformCallback, - load: loadCallback + load: loadCallback, })) } // We extract this check because all bundlers should behave the same -function checkHookCalls ( +function checkHookCalls( resolveIdCallback: Mock, transformIncludeCallback: Mock, transformCallback: Mock, - loadCallback: Mock + loadCallback: Mock, ): void { const EXPECT_CALLED_TIMES = 4 // Ensure that all bundlers call the hooks the same amount of times @@ -71,7 +73,7 @@ describe('id parameter should be consistent accross hooks and plugins', () => { mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, - mockLoadHook + mockLoadHook, ).vite // we need to define `enforce` here for the plugin to be run const plugins = toArray(plugin()).map((plugin): VitePlugin => ({ ...plugin, enforce: 'pre' })) @@ -82,13 +84,13 @@ describe('id parameter should be consistent accross hooks and plugins', () => { build: { lib: { entry: entryFilePath, - name: 'TestLib' + name: 'TestLib', }, rollupOptions: { - external: externals + external: externals, }, - write: false // don't output anything - } + write: false, // don't output anything + }, }) checkHookCalls(mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, mockLoadHook) @@ -104,13 +106,13 @@ describe('id parameter should be consistent accross hooks and plugins', () => { mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, - mockLoadHook + mockLoadHook, ).rollup await build.rollup({ input: entryFilePath, plugins: [plugin()], - external: externals + external: externals, }) checkHookCalls(mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, mockLoadHook) @@ -126,7 +128,7 @@ describe('id parameter should be consistent accross hooks and plugins', () => { mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, - mockLoadHook + mockLoadHook, ).webpack await new Promise((resolve) => { @@ -136,11 +138,11 @@ describe('id parameter should be consistent accross hooks and plugins', () => { plugins: [plugin()], externals, mode: 'production', - target: 'node' // needed for webpack 4 so it doesn't try to "browserify" any node externals and load addtional modules + target: 'node', // needed for webpack 4 so it doesn't try to "browserify" any node externals and load addtional modules }, () => { resolve() - } + }, ) }) @@ -157,7 +159,7 @@ describe('id parameter should be consistent accross hooks and plugins', () => { mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, - mockLoadHook + mockLoadHook, ).esbuild await build.esbuild({ @@ -165,7 +167,7 @@ describe('id parameter should be consistent accross hooks and plugins', () => { plugins: [plugin()], bundle: true, // actually traverse imports write: false, // don't pollute console - external: externals + external: externals, }) checkHookCalls(mockResolveIdHook, mockTransformIncludeHook, mockTransformHook, mockLoadHook) diff --git a/test/unit-tests/resolve-id-external/resolve-id-external.test.ts b/test/unit-tests/resolve-id-external/resolve-id-external.test.ts index d179ca92..302de79a 100644 --- a/test/unit-tests/resolve-id-external/resolve-id-external.test.ts +++ b/test/unit-tests/resolve-id-external/resolve-id-external.test.ts @@ -1,7 +1,8 @@ import * as path from 'path' -import { it, describe, expect, vi, afterEach } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { VitePlugin } from 'unplugin' +import { createUnplugin } from 'unplugin' import { build, toArray } from '../utils' -import { VitePlugin, createUnplugin } from 'unplugin' const entryFilePath = path.resolve(__dirname, './test-src/entry.js') const externals = ['path'] @@ -11,23 +12,24 @@ describe('load hook should not be called when resolveId hook returned `external: if (id === 'external-module') { return { id, - external: true + external: true, } - } else { + } + else { return null } }) const mockLoadHook = vi.fn(() => undefined) - function createMockedUnplugin () { + function createMockedUnplugin() { return createUnplugin(() => ({ name: 'test-plugin', resolveId: mockResolveIdHook, - load: mockLoadHook + load: mockLoadHook, })) } // We extract this check because all bundlers should behave the same - function checkHookCalls (): void { + function checkHookCalls(): void { expect(mockResolveIdHook).toHaveBeenCalledTimes(3) expect(mockResolveIdHook).toHaveBeenCalledWith(entryFilePath, undefined, expect.anything()) expect(mockResolveIdHook).toHaveBeenCalledWith('./internal-module.js', expect.anything(), expect.anything()) @@ -53,13 +55,13 @@ describe('load hook should not be called when resolveId hook returned `external: build: { lib: { entry: entryFilePath, - name: 'TestLib' + name: 'TestLib', }, rollupOptions: { - external: externals + external: externals, }, - write: false // don't output anything - } + write: false, // don't output anything + }, }) checkHookCalls() @@ -71,7 +73,7 @@ describe('load hook should not be called when resolveId hook returned `external: await build.rollup({ input: entryFilePath, plugins: [plugin()], - external: externals + external: externals, }) checkHookCalls() @@ -87,11 +89,11 @@ describe('load hook should not be called when resolveId hook returned `external: plugins: [plugin()], externals, mode: 'production', - target: 'node' // needed for webpack 4 so it doesn't try to "browserify" any node externals and load addtional modules + target: 'node', // needed for webpack 4 so it doesn't try to "browserify" any node externals and load addtional modules }, () => { resolve() - } + }, ) }) @@ -106,7 +108,7 @@ describe('load hook should not be called when resolveId hook returned `external: plugins: [plugin()], bundle: true, // actually traverse imports write: false, // don't pollute console - external: externals + external: externals, }) checkHookCalls() diff --git a/test/unit-tests/resolve-id/resolve-id.test.ts b/test/unit-tests/resolve-id/resolve-id.test.ts index 3831cb8e..f06f7c0d 100644 --- a/test/unit-tests/resolve-id/resolve-id.test.ts +++ b/test/unit-tests/resolve-id/resolve-id.test.ts @@ -1,41 +1,43 @@ import * as path from 'path' -import { it, describe, expect, vi, afterEach, Mock } from 'vitest' +import type { Mock } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { UnpluginOptions, VitePlugin } from 'unplugin' +import { createUnplugin } from 'unplugin' import { build, toArray } from '../utils' -import { createUnplugin, UnpluginOptions, VitePlugin } from 'unplugin' -function createUnpluginWithCallback (resolveIdCallback: UnpluginOptions['resolveId']) { +function createUnpluginWithCallback(resolveIdCallback: UnpluginOptions['resolveId']) { return createUnplugin(() => ({ name: 'test-plugin', - resolveId: resolveIdCallback + resolveId: resolveIdCallback, })) } // We extract this check because all bundlers should behave the same -function checkResolveIdHook (resolveIdCallback: Mock): void { +function checkResolveIdHook(resolveIdCallback: Mock): void { expect.assertions(4) expect(resolveIdCallback).toHaveBeenCalledWith( expect.stringMatching(/(?:\/|\\)entry\.js$/), undefined, - expect.objectContaining({ isEntry: true }) + expect.objectContaining({ isEntry: true }), ) expect(resolveIdCallback).toHaveBeenCalledWith( './proxy-export', expect.stringMatching(/(?:\/|\\)entry\.js$/), - expect.objectContaining({ isEntry: false }) + expect.objectContaining({ isEntry: false }), ) expect(resolveIdCallback).toHaveBeenCalledWith( './default-export', expect.stringMatching(/(?:\/|\\)proxy-export\.js$/), - expect.objectContaining({ isEntry: false }) + expect.objectContaining({ isEntry: false }), ) expect(resolveIdCallback).toHaveBeenCalledWith( './named-export', expect.stringMatching(/(?:\/|\\)proxy-export\.js$/), - expect.objectContaining({ isEntry: false }) + expect.objectContaining({ isEntry: false }), ) } @@ -56,10 +58,10 @@ describe('resolveId hook', () => { build: { lib: { entry: path.resolve(__dirname, 'test-src/entry.js'), - name: 'TestLib' + name: 'TestLib', }, - write: false // don't output anything - } + write: false, // don't output anything + }, }) checkResolveIdHook(mockResolveIdHook) @@ -71,7 +73,7 @@ describe('resolveId hook', () => { await build.rollup({ input: path.resolve(__dirname, 'test-src/entry.js'), - plugins: [plugin()] + plugins: [plugin()], }) checkResolveIdHook(mockResolveIdHook) @@ -85,9 +87,9 @@ describe('resolveId hook', () => { build.webpack( { entry: path.resolve(__dirname, 'test-src/entry.js'), - plugins: [plugin()] + plugins: [plugin()], }, - resolve + resolve, ) }) @@ -102,7 +104,7 @@ describe('resolveId hook', () => { entryPoints: [path.resolve(__dirname, 'test-src/entry.js')], plugins: [plugin()], bundle: true, // actually traverse imports - write: false // don't pollute console + write: false, // don't pollute console }) checkResolveIdHook(mockResolveIdHook) diff --git a/test/unit-tests/utils.ts b/test/unit-tests/utils.ts index d594f31e..7182ed11 100644 --- a/test/unit-tests/utils.ts +++ b/test/unit-tests/utils.ts @@ -16,5 +16,5 @@ export const build = { webpack: webpackBuild, rollup: rollupBuild, vite: viteBuild, - esbuild: esbuildBuild + esbuild: esbuildBuild, } diff --git a/test/unit-tests/write-bundle/write-bundle.test.ts b/test/unit-tests/write-bundle/write-bundle.test.ts index af498937..14d9d435 100644 --- a/test/unit-tests/write-bundle/write-bundle.test.ts +++ b/test/unit-tests/write-bundle/write-bundle.test.ts @@ -1,17 +1,19 @@ import * as path from 'path' import * as fs from 'fs' -import { it, describe, expect, vi, afterEach, Mock, beforeAll } from 'vitest' +import type { Mock } from 'vitest' +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import type { UnpluginOptions, VitePlugin } from 'unplugin' +import { createUnplugin } from 'unplugin' import { build, toArray, webpackVersion } from '../utils' -import { createUnplugin, UnpluginOptions, VitePlugin } from 'unplugin' -function createUnpluginWithCallback (writeBundleCallback: UnpluginOptions['writeBundle']) { +function createUnpluginWithCallback(writeBundleCallback: UnpluginOptions['writeBundle']) { return createUnplugin(() => ({ name: 'test-plugin', - writeBundle: writeBundleCallback + writeBundle: writeBundleCallback, })) } -function generateMockWriteBundleHook (outputPath: string) { +function generateMockWriteBundleHook(outputPath: string) { return () => { // We want to check that at the time the `writeBundle` hook is called, all // build-artifacts have already been written to disk. @@ -27,7 +29,7 @@ function generateMockWriteBundleHook (outputPath: string) { } // We extract this check because all bundlers should behave the same -function checkWriteBundleHook (writeBundleCallback: Mock): void { +function checkWriteBundleHook(writeBundleCallback: Mock): void { expect(writeBundleCallback).toHaveBeenCalledOnce() } @@ -55,11 +57,11 @@ describe('writeBundle hook', () => { entry: path.resolve(__dirname, 'test-src/entry.js'), name: 'TestLib', fileName: 'output', - formats: ['cjs'] + formats: ['cjs'], }, outDir: path.resolve(__dirname, 'test-out/vite'), - sourcemap: true - } + sourcemap: true, + }, }) checkWriteBundleHook(mockWriteBundleHook) @@ -71,7 +73,7 @@ describe('writeBundle hook', () => { const plugin = createUnpluginWithCallback(mockResolveIdHook).rollup const rollupBuild = await build.rollup({ - input: path.resolve(__dirname, 'test-src/entry.js') + input: path.resolve(__dirname, 'test-src/entry.js'), }) await rollupBuild.write({ @@ -79,7 +81,7 @@ describe('writeBundle hook', () => { file: path.resolve(__dirname, 'test-out/rollup/output.js'), format: 'cjs', exports: 'named', - sourcemap: true + sourcemap: true, }) checkWriteBundleHook(mockResolveIdHook) @@ -96,10 +98,10 @@ describe('writeBundle hook', () => { output: { path: path.resolve(__dirname, 'test-out/webpack'), filename: 'output.js', - libraryTarget: 'commonjs' + libraryTarget: 'commonjs', }, plugins: [plugin()], - devtool: 'source-map' + devtool: 'source-map', } const webpack5Options = { @@ -110,14 +112,14 @@ describe('writeBundle hook', () => { path: path.resolve(__dirname, 'test-out/webpack'), filename: 'output.js', library: { - type: 'commonjs' - } - } + type: 'commonjs', + }, + }, } await new Promise((resolve) => { build.webpack(webpackVersion!.startsWith('4') ? webpack4Options : webpack5Options, - resolve + resolve, ) }) @@ -135,7 +137,7 @@ describe('writeBundle hook', () => { bundle: true, // actually traverse imports outfile: path.resolve(__dirname, 'test-out/esbuild/output.js'), format: 'cjs', - sourcemap: true + sourcemap: true, }) checkWriteBundleHook(mockResolveIdHook) diff --git a/tsup.config.ts b/tsup.config.ts index 24e23d93..dec6bc11 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -10,15 +10,15 @@ export const tsup: Options = { entryPoints: [ 'src/index.ts', 'src/webpack/loaders/load.ts', - 'src/webpack/loaders/transform.ts' + 'src/webpack/loaders/transform.ts', ], external: [ 'vite', 'webpack', 'rollup', - 'esbuild' + 'esbuild', ], define: { - __DEV__: 'false' - } + __DEV__: 'false', + }, } diff --git a/vitest.config.ts b/vitest.config.ts index bba42927..85e5f976 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,11 +3,11 @@ import { defineConfig } from 'vite' export default defineConfig({ define: { - __DEV__: 'true' + __DEV__: 'true', }, resolve: { alias: { - unplugin: resolve('src/index.ts') - } - } + unplugin: resolve('src/index.ts'), + }, + }, }) From 4ff6c33fd402de157d49b5c90133a8ec85af5a60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90?= Date: Sat, 29 Oct 2022 15:29:51 +0800 Subject: [PATCH 2/3] ci: add lint --- .github/workflows/ci.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ec68bb2..2c9bd43d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,24 @@ on: - main jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set node + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Setup + run: npm i -g @antfu/ni + + - name: Install + run: nci + + - name: Lint + run: nr lint + ci: runs-on: ${{ matrix.os }} From df92ec93d46e9d2df660855969aaabb5a2535edd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90?= Date: Sat, 29 Oct 2022 15:49:48 +0800 Subject: [PATCH 3/3] fix: TS type errors --- src/rollup/index.ts | 10 +++++----- src/types.ts | 4 ++-- src/vite/index.ts | 10 +++++----- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/rollup/index.ts b/src/rollup/index.ts index 4b6f2024..5d9b5f89 100644 --- a/src/rollup/index.ts +++ b/src/rollup/index.ts @@ -1,17 +1,17 @@ import type { RollupPlugin, UnpluginContextMeta, UnpluginFactory, UnpluginInstance, UnpluginOptions } from '../types' import { toArray } from '../utils' -export function getRollupPlugin ( - factory: UnpluginFactory, -): UnpluginInstance['rollup'] { - return (userOptions?: UserOptions) => { +export function getRollupPlugin ( + factory: UnpluginFactory, +) { + return ((userOptions?: UserOptions) => { const meta: UnpluginContextMeta = { framework: 'rollup', } const rawPlugins = toArray(factory(userOptions!, meta)) const plugins = rawPlugins.map(plugin => toRollupPlugin(plugin)) return plugins.length === 1 ? plugins[0] : plugins - } + }) as UnpluginInstance['rollup'] } export function toRollupPlugin(plugin: UnpluginOptions, containRollupOptions = true): RollupPlugin { diff --git a/src/types.ts b/src/types.ts index 2322bac8..3fcd1ee5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -69,7 +69,7 @@ export interface ResolvedUnpluginOptions extends UnpluginOptions { __virtualModulePrefix: string } -export type UnpluginFactory = (options: UserOptions, meta: UnpluginContextMeta) => +export type UnpluginFactory = (options: UserOptions, meta: UnpluginContextMeta) => Nested extends true ? Array : UnpluginOptions @@ -77,7 +77,7 @@ export type UnpluginFactoryOutput = undefined extends UserO ? (options?: UserOptions) => Return : (options: UserOptions) => Return -export interface UnpluginInstance { +export interface UnpluginInstance { rollup: UnpluginFactoryOutput : RollupPlugin> vite: UnpluginFactoryOutput : VitePlugin> webpack: UnpluginFactoryOutput diff --git a/src/vite/index.ts b/src/vite/index.ts index f9eec52f..2a1824ad 100644 --- a/src/vite/index.ts +++ b/src/vite/index.ts @@ -2,10 +2,10 @@ import { toRollupPlugin } from '../rollup' import type { UnpluginContextMeta, UnpluginFactory, UnpluginInstance, VitePlugin } from '../types' import { toArray } from '../utils' -export function getVitePlugin ( - factory: UnpluginFactory, -): UnpluginInstance['vite'] { - return (userOptions?: UserOptions) => { +export function getVitePlugin ( + factory: UnpluginFactory, +) { + return ((userOptions?: UserOptions) => { const meta: UnpluginContextMeta = { framework: 'vite', } @@ -20,5 +20,5 @@ export function getVitePlugin ( }) return plugins.length === 1 ? plugins[0] : plugins - } + }) as UnpluginInstance['vite'] }