michalkvasnicak / babel-plugin-css-modules-transform

Extract css class names from required css module files, so we can render it on server.
MIT License
326 stars 54 forks source link

Using Node's require to resolve file path does not resolve correct library from node_modules #97

Open nkbt opened 5 years ago

nkbt commented 5 years ago

This issue is quite tricky to even report and I understand if you just close it as "cannot reproduce". I even thought about not opening this issue as it is quite hard to explain. But it may be somewhat helpful for others, so I will do my best to explain the problem.

The issue is in this function requireCssFile https://github.com/michalkvasnicak/babel-plugin-css-modules-transform/blob/master/src/index.js#L52-L72

I've added to the start of it

console.log(require.resolve.paths('@myscope/my-lib/Styles.css'))
process.exit(1)

And I am getting this

[
  '/Users/nkbt/test/node_modules/babel-plugin-css-modules-transform/build/node_modules',
  '/Users/nkbt/test/node_modules/babel-plugin-css-modules-transform/node_modules',
  '/Users/nkbt/test/node_modules',
  '/Users/nkbt/node_modules',
...
]

That seems like a correct list of paths to look for libs, but the real problem is that I am doing build within nested subfolder which has it's own node_modules inside

console.log(`process.cwd()`, process.cwd())

> process.cwd() /Users/nkbt/test/.pk/services/my-service/docker/app

This is what I would expect instead (check with just node, not going through the build loop)

$ node
> process.cwd()
'/Users/nkbt/test/.pk/services/my-service/docker/app'
> require.resolve.paths('@myscope/my-lib/Styles.css')
[
  '/Users/nkbt/test/.pk/services/my-service/docker/app/repl/node_modules',
  '/Users/nkbt/test/.pk/services/my-service/docker/app/node_modules',
  '/Users/nkbt/test/.pk/services/my-service/docker/node_modules',
  '/Users/nkbt/test/.pk/services/my-service/node_modules',
  '/Users/nkbt/test/.pk/services/node_modules',
  '/Users/nkbt/test/.pk/node_modules',
  '/Users/nkbt/test/node_modules',
  ...
]

I do not know too much about writing babel transforms, but I assume it may provide some context similar to cwd() from where files/libs need to be searched

I did not check but very much certain same problem would happen if I am to use global installation of babel/babel-plugin-css-modules-transform, because it would resolve to a babel-plugin-css-modules-transform folder in node directory and not the app one.

For the moment my only solution would be to not import css from a package directly, but update package so it exports css, because if paths are relative, this transform works ok.