TypeScript: How to add an absolute path to the root directory to import files from there?

377 Views Asked by At

I have my TS config:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
    },
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": false,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "jest.config.js"],
  "exclude": ["node_modules", ".next", "out", "build", "coverage"]

And want to reference a TS file in the root directory for one of my components so it is cleaner:

import React from 'react';
import { withTranslation, Link } from '../../../i18n';

const Header = (): JSX.Element => {
  return (
    <>
      <Flex>
        <Box>
          <Link href="/">HOME</Link>
        </Box>
      </Flex>
    </>
  );
};

export default Header;

How do I update the tsconfig to reference the i18n absolutely?

1

There are 1 best solutions below

0
On

Assuming your i18n folder is in the root, you can use the paths property in the tsconfig.

More info here

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
       "i18n": ["i18n"]
    },
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": false,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "jest.config.js"],
  "exclude": ["node_modules", ".next", "out", "build", "coverage"]
}
import React from 'react';
import { withTranslation, Link } from 'i18n';

const Header = (): JSX.Element => {
  return (
    <>
      <Flex>
        <Box>
          <Link href="/">HOME</Link>
        </Box>
      </Flex>
    </>
  );
};

export default Header;