Home > Software engineering >  Typescript: baseUrl doesn't work when importing from subfolder?
Typescript: baseUrl doesn't work when importing from subfolder?

Time:12-01

I have a file located in src/components/SvgIcon/SvgIcon.stories.tsx. Inside it, I try to import like this:

src/components/SvgIcon/SvgIcon.stories.tsx

import { SVG_ICON_SIZES, SVG_ICON_COLORS } from 'constants/properties';

However, it keeps complaining with this error: Cannot find module 'constants/properties' or its corresponding type declarations.

There's nothing special going on in my properties.ts file:

src/constants/properties.ts

export enum SVG_ICON_SIZES {
  SMALL = 'small',
  MEDIUM = 'medium',
  LARGE = 'large',
  XL = 'xl',
}

export enum SVG_ICON_COLORS {
  PRIMARY = 'primary',
  SECONDARY = 'secondary',
  DISABLED = 'disabled',
  NEGATIVE = 'negative',
  WARNING = 'warning',
  POSITIVE = 'positive',
  INTERACTIVE = 'interactive',
  LIGHT = 'light',
}

This is what my tsconfig.json looks like:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "baseUrl": "src",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "declarationDir": "dist",
    "emitDeclarationOnly": true,
    "strict": true,
    "strictNullChecks": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react",
    "types": ["jest"],
    "typeRoots": ["src/types", "node_modules/@types"]
  },
  "include": ["src"],
  "exclude": ["node_modules", "src/**/*.stories.tsx"]
}

In my less nested file, everything works as expected:

src/components/Menu.tsx

enter image description here

Why is it not working in the subfolder?

CodePudding user response:

Figured it out. It was because I had this in my exclude in tsconfig.json:

"exclude": ["node_modules", "src/**/*.stories.tsx"]

Updated it to

"exclude": ["node_modules"]

and now it works

CodePudding user response:

Without knowing your file/directory structure, have you tried?

import { SVG_ICON_SIZES, SVG_ICON_COLORS } from './constants/properties';

Or stopping and restarting your project.

I've got one project that randomly refuses to pick up on newly created files - fixing it is not in my top 20 things to do

  • Related