johvin / eslint-import-resolver-alias

a simple Node behavior import resolution plugin for eslint-plugin-import, supporting module alias
MIT License
180 stars 10 forks source link

Throw errors when resolving packages whose "main" is set to a folder (i.e enzyme) #18

Open zeroliu opened 4 years ago

zeroliu commented 4 years ago

When using eslint-import-resolver-alias with enzyme, it throws an error.

// item.test.tsx
import { shallow } from 'enzyme';
// .eslint.json
"settings": {
  "import/resolver": {
    "alias": {
      "map": [["src", "./src"]],
      "extensions": [".ts", ".tsx"]
    }
  }
}
1:1  error  Resolve error: Cannot find module '/Users/zeroliu/Developer/Advanced-React/sick-fits/frontend/node_modules/enzyme/build'. Please verify that the package.json has a valid "main" entry
    at tryPackage (internal/modules/cjs/loader.js:323:19)
    at Function.Module._findPath (internal/modules/cjs/loader.js:680:18)
    at findModulePath (/Users/zeroliu/Developer/Advanced-React/sick-fits/frontend/node_modules/eslint-import-resolver-alias/index.js:100:27)

It works for other packages. The error goes away if I stop importing enzyme or remove eslint-import-resolver-alias from my pipeline. Looking at enzyme package.json, its "main" property is set to "build" folder, which is different from most NPM packages that use a js file as entry. According to the call stack, I believe the problem is caused by calling the private __findPath method directly.

const filename = Module._findPath(request, paths);

I'm not quite familiar with the internal implementation of node module. Please help.

For now, there are these workarounds:

  1. map enzyme to a random path.

    "map": [["src", "./src"], ["enzyme", "foo"]]
  2. update enzyme package.json main to "build/index.js"

Option 1 is probably better since we don't want to touch third party packages.

ming436534 commented 4 years ago

I forked this project and added a quite hacky code to ignore this "main" problem, you might check this out

https://github.com/ming436534/eslint-import-resolver-alias