solana-labs / eslint-plugin-require-extensions

Apache License 2.0
53 stars 6 forks source link

False-negative on JSON import #1

Closed tpluscode closed 1 year ago

tpluscode commented 1 year ago

This could potentially affect other non-script imports?

I have in my code this import:

import mockObjects from './mock-data.json' assert { type: 'json' }

The plugin complains and when "fixed", it changes that line into

import mockObjects from './mock-data.json.js' assert { type: 'json' }

I think that rule should only apply to some pattern, like/.+(t|j)s(x)?/ by default. Possibly configurable.

tpluscode commented 1 year ago

Here's how I modified the rule to only apply to js(x) and ts(x) imported modules

diff --git a/node_modules/eslint-plugin-require-extensions/index.js b/node_modules/eslint-plugin-require-extensions/index.js
index d531a5e..bf1a83c 100644
--- a/node_modules/eslint-plugin-require-extensions/index.js
+++ b/node_modules/eslint-plugin-require-extensions/index.js
@@ -1,3 +1,14 @@
+const { existsSync } = require('fs')
+const { dirname, resolve } = require('path')
+
+const extensions = ['js', 'ts', 'jsx', 'tsx']
+
+function moduleExists(path) {
+  return ext => {
+    return existsSync(`${path}.${ext}`)
+  }
+}
+
 module.exports = {
     configs: {
         recommended: {
@@ -19,7 +30,9 @@ module.exports = {
                     const value = source.value;
                     if (!value) return;

-                    if (value.startsWith('.') && !value.endsWith('.js')) {
+                    if (!value.startsWith('.') || value.endsWith('.js')) return;
+
+                    if (extensions.some(moduleExists(resolve(dirname(context.getFilename()), value)))) {
                         context.report({
                             node,
                             message: 'Relative imports and exports must end with .js',
steelerc69 commented 1 year ago

is this planned on getting accepted?