Skip to content

Commit

Permalink
Add no-unnecessary-polyfills rule
Browse files Browse the repository at this point in the history
Fixes: #36
  • Loading branch information
Mesteery committed Jul 1, 2023
1 parent 03d24e7 commit bb65c06
Show file tree
Hide file tree
Showing 6 changed files with 394 additions and 0 deletions.
1 change: 1 addition & 0 deletions configs/recommended.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ module.exports = {
'unicorn/no-this-assignment': 'error',
'unicorn/no-typeof-undefined': 'error',
'unicorn/no-unnecessary-await': 'error',
'unicorn/no-unnecessary-polyfills': 'error',
'unicorn/no-unreadable-array-destructuring': 'error',
'unicorn/no-unreadable-iife': 'error',
'unicorn/no-unused-properties': 'off',
Expand Down
68 changes: 68 additions & 0 deletions docs/rules/no-unnecessary-polyfills.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Enforce the use of built-in methods instead of unnecessary polyfills

💼 This rule is enabled in the ✅ `recommended` [config](https://github.com/sindresorhus/eslint-plugin-unicorn#preset-configs).

<!-- end auto-generated rule header -->

<!-- Do not manually modify RULE_NOTICE part. Run: `npm run generate-rule-notices` -->
<!-- RULE_NOTICE -->
*This rule is part of the [recommended](https://github.com/sindresorhus/eslint-plugin-unicorn#recommended-config) config.*
<!-- /RULE_NOTICE -->

This rules helps to use existing methods instead of using extra polyfills.

## Fail

package.json

```json
{
"engines": {
"node": ">=8"
}
}
```

```js
const assign = require('object-assign');
```

## Pass

package.json

```json
{
"engines": {
"node": "4"
}
}
```

```js
const assign = require('object-assign'); // passes as Object.assign is not supported
```

## Options

Type: `object`

### targets

Type: `string | string[] | object`

The `targets` option allows to specify the target versions. This option could be a Browserlist query or a targets object, see [core-js-compat `targets` option](https://github.com/zloirock/core-js/tree/HEAD/packages/core-js-compat#targets-option) for more informations.

If the option is not specified, target versions are defined using the `browserlist` field, or as a last resort the `engines` field, of `package.json`.

```js
"unicorn/no-unnecessary-polyfills": ["error", { "targets": "node >=12" }]
```

```js
"unicorn/no-unnecessary-polyfills": ["error", { "targets": ["node 14.1.0", "chrome 95"] }]
```

```js
"unicorn/no-unnecessary-polyfills": ["error", { "targets": { "node": "current", "firefox": "15" } }]
```
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@eslint-community/eslint-utils": "^4.4.0",
"ci-info": "^3.8.0",
"clean-regexp": "^1.0.0",
"core-js-compat": "^3.21.0",
"esquery": "^1.5.0",
"indent-string": "^4.0.0",
"is-builtin-module": "^3.2.1",
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ If you don't use the preset, ensure you use the same `env` and `parserOptions` c
| [no-this-assignment](docs/rules/no-this-assignment.md) | Disallow assigning `this` to a variable. || | |
| [no-typeof-undefined](docs/rules/no-typeof-undefined.md) | Disallow comparing `undefined` using `typeof`. || 🔧 | 💡 |
| [no-unnecessary-await](docs/rules/no-unnecessary-await.md) | Disallow awaiting non-promise values. || 🔧 | |
| [no-unnecessary-polyfills](docs/rules/no-unnecessary-polyfills.md) | Enforce the use of built-in methods instead of unnecessary polyfills. || | |
| [no-unreadable-array-destructuring](docs/rules/no-unreadable-array-destructuring.md) | Disallow unreadable array destructuring. || 🔧 | |
| [no-unreadable-iife](docs/rules/no-unreadable-iife.md) | Disallow unreadable IIFEs. || | |
| [no-unused-properties](docs/rules/no-unused-properties.md) | Disallow unused object properties. | | | |
Expand Down
147 changes: 147 additions & 0 deletions rules/no-unnecessary-polyfills.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
'use strict';
const readPkgUp = require('read-pkg-up');
const coreJsCompat = require('core-js-compat');
const {camelCase} = require('lodash');
const isStaticRequire = require('./ast/is-static-require.js');

const {data: compatData, entries: coreJsEntries} = coreJsCompat;

const MESSAGE_ID_POLYFILL = 'unnecessaryPolyfill';
const MESSAGE_ID_CORE_JS = 'unnecessaryCoreJsModule';
const messages = {
[MESSAGE_ID_POLYFILL]: 'Use built-in instead.',
[MESSAGE_ID_CORE_JS]:
'All polyfilled features imported from `{{coreJsModule}}` are available as built-ins. Use the built-ins instead.',
};

const additionalPolyfillPatterns = {
'es.promise.finally': '|(p-finally)',
'es.object.set-prototype-of': '|(setprototypeof)',
'es.string.code-point-at': '|(code-point-at)',
};

const prefixes = '(mdn-polyfills/|polyfill-)';
const suffixes = '(-polyfill)';
const delimiter = '(\\.|-|\\.prototype\\.|/)?';

const polyfills = Object.keys(compatData).map(feature => {
let [ecmaVersion, constructorName, methodName = ''] = feature.split('.');

if (ecmaVersion === 'es') {
ecmaVersion = `(${ecmaVersion}\\d*)`;
}

constructorName = `(${constructorName}|${camelCase(constructorName)})`;
methodName &&= `(${methodName}|${camelCase(methodName)})`;

const methodOrConstructor = methodName || constructorName;

const patterns = [
`^((${prefixes}?`,
`((${ecmaVersion}${delimiter}${constructorName}${delimiter}${methodName})|`, // Ex: es6-array-copy-within
`(${constructorName}${delimiter}${methodName})|`, // Ex: array-copy-within
`(${ecmaVersion}${delimiter}${constructorName}))`, // Ex: es6-array
`${suffixes}?)|`,
`(${prefixes}${methodOrConstructor}|${methodOrConstructor}${suffixes})`, // Ex: polyfill-copy-within / polyfill-promise
`${additionalPolyfillPatterns[feature] || ''})$`,
];

return {
feature,
pattern: new RegExp(patterns.join(''), 'i'),
};
});

function getTargets(options) {
if (options?.targets) {
return options.targets;
}

const result = readPkgUp.sync();
if (!result?.pkg) {
return;
}

return result.pkg.browserlist || result.pkg.engines;
}

function create(context) {
const unavailableFeatures = coreJsCompat({targets: getTargets(context.options[0])}).list;
const checkFeatures = features => !features.every(feature => unavailableFeatures.includes(feature));

return {
Literal(node) {
if (
!(
((node.parent.type === 'ImportDeclaration' || node.parent.type === 'ImportExpression')
&& node.parent.source === node)
|| (isStaticRequire(node.parent) && node.parent.arguments[0] === node)
)
) {
return;
}

const importedModule = node.value;
if (typeof importedModule !== 'string' || ['.', '/'].includes(importedModule[0])) {
return;
}

const coreJsModuleFeatures = coreJsEntries[importedModule.replace('core-js-pure', 'core-js')];

if (coreJsModuleFeatures) {
if (coreJsModuleFeatures.length > 1) {
if (checkFeatures(coreJsModuleFeatures)) {
return {
node,
messageId: MESSAGE_ID_CORE_JS,
data: {
coreJsModule: importedModule,
},
};
}
} else if (!unavailableFeatures.includes(coreJsModuleFeatures[0])) {
return {node, messageId: MESSAGE_ID_POLYFILL};
}

return;
}

const polyfill = polyfills.find(({pattern}) => pattern.test(importedModule));
if (polyfill) {
const [, namespace, method = ''] = polyfill.feature.split('.');
const [, features] = Object.entries(coreJsEntries).find(
it => it[0] === `core-js/actual/${namespace}${method && '/'}${method}`,
);
if (checkFeatures(features)) {
return {node, messageId: MESSAGE_ID_POLYFILL};
}
}
},
};
}

const schema = [
{
type: 'object',
additionalProperties: false,
required: ['targets'],
properties: {
targets: {
oneOf: [{type: 'string'}, {type: 'array'}, {type: 'object'}],
},
},
},
];

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Enforce the use of built-in methods instead of unnecessary polyfills.',
},
schema,
messages,
},
};
Loading

0 comments on commit bb65c06

Please sign in to comment.