Is there any way right now to resolve modules absolutely relative to the project directory?
For example inside a file in the pages directory:
import Title from 'components/title'
where the components directory is next to the pages directory.
This would be nice so that we don't have to write long relative paths for nested directories.
You can create a components directory inside the node_modules directory and then use components/title. But since the babel-loader in the webpack configuration exclude node_modules you can't made use of JSX and everything Node.js don't support right now.
When #222 be merged you will be able to able to configure aliases (or custom modules directories) in the webpack configuration.
Maybe this can be added to the next.js configuration, but then everyone should use a components directory next to the pages directory to get this aliases to work. I'm not sure this is something the next.js team want to force in every developer who use it.
@rovansteen @sergiodxa Next.js supports NODE_PATH env variable.
See: https://github.com/zeit/next.js/pull/233
You can . as the NODE_PATH and do absolute imports. You can add multiple of them as well separated by the OS's seperators. ( ":" in Unix and ";" in windows )
@arunoda yeah I saw that issue but that's not working for me because the files are imported that way are not transpiled through babel. Is that correct?
@sergiodxa that was something I tried as well but ran into the issue you described. Guess I'll have to wait until #222 is merged. Thanks anyway!
@rovansteen no. It should work properly.
Next.js wepack instance is configured to read NODE_PATH.
If that's not working it's a bug.
I suggest babel-root-import
It can be configured to support multiple paths.
I found this approach very useful when doing refactoring.
@arunoda when using NODE_PATH I'm getting the classic SyntaxError: Unexpected token import error so it doesn't seem to be transpiled through babel. Same goes for using babel-root-import @foxhound87.
Correction, babel-root-import does work, got my babel configuration wrong. Thanks for the tip @foxhound87. But the issue still remains for the NODE_PATH.
@rovansteen Yep. NODE_PATH is not working properly.
I've look at this again.
We do support NODE_PATH but it's not for this case. We support it to load NPM modules.
(Which are pre-transpiled)
We do support absolute modules via NODE_PATH in webpack environment. But for SSR, it won't work well. I tried fixing a lot of stuff, even hijacking node's module system or introduce a different env variable. This is doable, but feels hacky.
Since we've a solution via babel-root-import, it's not worthy to go for a hack.
Most helpful comment
Correction,
babel-root-importdoes work, got my babel configuration wrong. Thanks for the tip @foxhound87. But the issue still remains for theNODE_PATH.