JavaScript absolute import including package name

I'm using Create React App and Yarn workspaces and have all my code in packages. Here is an example of my workspace structure.

workspace
apps
src
app1
packages
common
components
a
b
c
Component1
d
e
f
Component2

I do my builds from `workspace/apps/src/app1` so relative paths are all from there. Component2 needs to import Component1 and since they're in the same package IntelliJ imports using this.

import Component1 from '../../../a/b/c/Component1';

If I change Settings -> Editor -> Code Style -> JavaScript -> Imports -> 'Use paths relative to the project, resource or sources roots' on it will do this

import Component1 from 'components/a/b/c/Component1';

This doesn't work since I'm building in `workspace/apps/src/app1` and it tries to find the file in `src/app1/components/a/b/c/Component1`

In `packages/common/package.json` I have "name": "@company/common" and I need to have the import be this even if the file is in the same package.

import Component1 from '@company/common/components/a/b/c/Component1';

I've tried all kinds of things and no luck. How can I do this?

5 comments
Comment actions Permalink

In monorepo projects, package imports ('@company/common/components/a/b/c/Component1') are used when importing modules from different packages, but files from the same package are imported using relative paths. This is expected, and there is no way to change this... If you need it to work differently, please file a feature request to youtrack, providing a sample project

0
Comment actions Permalink

Should I file to WebStorm or IntelliJ and also what's the best way to share a sample project? 

0
Comment actions Permalink

To WebStorm - https://youtrack.jetbrains.com/issues/WEB

You can attach a sample project to youtrack ticket, or provide a link to github (or dropbox, or whatever file server you prefer)

0
Comment actions Permalink

A little change of direction and I've changed my Yarn workspace (monorepo) to have an index.js in each package root folder. In doing this I want my imports to work like this:

import { Header } from '@company/core';

Using alt-Enter only provides an option to import using:

import Header from '@company/core/src/components/Header';

I've tried all kinds of settings in Settings -> Editor -> Code Style -> JavaScript -> Imports and can't get it to use the first way. How can I get IntelliJ to always use imports from index.js instead of deep imports to the actual source?

Sample project is here (make sure you're on the cra-fork branch).

https://github.com/MikeSuiter/cra2-alpha-yarn-workspace/tree/cra-fork 

Open the project in IntelliJ and using a command prompt run 'yarn' to download the dependencies. Open 'apps/app-shared/src/App.js' and comment out the line 4 import. Put your cursor on '<Header' and press alt-Enter and it only offer the import style on line 3.

 

0

Please sign in to leave a comment.