Can I import submodules outside of the "main": "index.js" file from a local yarn workspace dependency package?

Viewed 592

I have the following monorepo structure (using yarn workspaces).

packages
  common
    src
      index.js
      module1.js
      module2.js
    package.json
  user
    src
      index.js
      moduleA.js
      mobuleB.js
    package.json
package.json

My root package.json

{
  "private": true,
  "workspaces": ["packages/*"]
}

package.json from common

{
  "name": "@packages/common",
  "version": "1.0.0",
  "main": "src/index.js",
  "license": "MIT"
}

package.json from user

{
  "name": "@packages/user",
  "version": "1.0.0",
  "main": "src/index.js",
  "license": "MIT",
  "dependencies": {
    "@packages/common": "1.0.0"
  }
}

As expected, the user package needs to "use / import" from the common package.

Here is my question: if I want to import module1 or module2 from the common package. Is there a way to do it directly, like:

import { Foo } from "@packages/common/src/module1";

Is this an anti-pattern? Should I only import from @packages/common, which would imply importing from common/src/index.js (given the main property on package.json)?

I pretty much would like to have access to any src/sub-folder/sub-file from the common package. Should I import | re-export everything from the common/src/index.js file, or is there a way to get those other files directly?

1 Answers

Yes you can. The following should work just fine:

import { Foo } from "@packages/common/src/module1";

OBS: The following details are specific for Next.js projects, but the idea might be the same for other projects.

Just keep in mind that if you need those files (the ones that live outside of your next project folder) to be transpiled, you're gonna need to use the next-transpile-modules package.

More details can be found here:

Related