React: Flow: Import a local js file - cannot resolve issue module

3.6k Views Asked by At

I am using Flow: Static type checking library for react front end application, it throws "cannot resolve" for internal imports from src directory:

Example in file at path: src/abc/def/ghi/hello.jsx, I am using the following import:
import words from '../words';

--> Throws error "Cannot resolve module ../words

words.js is in src/abc/def dir

EDITED: My .flowconfig looks like this after I installed flow-typed:

[ignore]
.*/node_modules/.*
.*/build/.*
.*/dist/.*


[include]
.*/src/.*
.*/test/.*

[libs]
flow-typed

[lints]

[options]
all=true
module.system.node.resolve_dirname=node_modules
module.system.node.resolve_dirname=src

[strict]

How do I map flow for such imports in .flowconfig file ?

Thanks in advance.

4

There are 4 best solutions below

0
On BEST ANSWER

Got it working.

Relative paths don't really work with Flow.

We need to map imports from Project root for Flow to understand.

I changed my import to

import words from 'def/words';

Add the following to your .flowconfig file

module.name_mapper='^def\(.*\)$' -> '<PROJECT_ROOT>/src/abc/def/\1'

Fixes above error.

0
On

In my case problem was that I use relative paths with webpack e.g

resolve: {
    modules: [
         path.resolve(__dirname, 'src'),
         ...
    ]
}

So, I can import my custom module from src like that (without write src/)

import CustomModule from 'pages/CustomModule'

But flow doesnt now about that webpack config, so I must add in my .flowconfig file next code

[options]
module.name_mapper='src' -> '<PROJECT_ROOT>/src'

More info

about flow options

about name_mapper

3
On

To get to ./def from ./hello.jsx, you have to go up another directory

import words from '../../words';

0
On
/path/to/project/node_modules/.bin/flow stop
/path/to/project/yarn run flow (or your flow invoking script)

this fixed the problem for me.