Typescript absolute import path

Intro

Working extensively with typescript for quite some time now being someone who adopted typescript at an early stage (just 4 months after learning Javascript). I have learned and benefited a lot from the features typescript offers, one of them is being able to use absolute paths to import modules. This feature is also available in Javascript as well but in this guide, I would mostly be talking about Typescript (no harsh feeling JS) and my IDE of choice is Vscode which this feature works without any additional configuration, In other editors like WebStorm, you may have to do some extra configurations to make this work more on that in this article written by Aman Kumar.

The tsconfig.json file

If you have worked with typescript for some amount of time, you would most likely have encountered this file. Similar to the package.json file or a docker file (for docker configs), this is where the configurations for your typescript compilation are written. You can generate this file with the tsc —init command but most frameworks using typescript would package this file for you.

Читайте также:  Php проверяем первую букву

Taking a look at relative paths

We’ll be taking a look at a nextJs project and see the horrors of using relative paths.

Our folder structure

. ├── README.md ├── next-env.d.ts ├── next.config.js ├── package.json ├── src │ ├── components │ │ ├── cards │ │ │ ├── featured-motion-card.tsx │ │ │ └── testimonal-card.tsx │ │ ├── footer │ │ │ └── index.tsx │ │ ├── icon-components │ │ │ ├── app-icon.tsx │ │ │ ├── instagram-icon.tsx │ │ │ ├── medium-icon.tsx │ │ │ ├── quoteLeft.tsx │ │ │ ├── twitter-icon.tsx │ │ │ ├── verified-icon.tsx │ │ │ └── youtube-icon.tsx │ │ ├── layouts │ │ │ └── index.tsx │ │ └── navbar.tsx │ ├── pages │ │ ├── _app.tsx │ │ ├── api │ │ │ └── hello.ts │ │ ├── auth │ │ │ ├── sign-in.tsx │ │ │ └── sign-up.tsx │ │ ├── communities │ │ │ └── index.tsx │ │ ├── index.tsx │ │ └── live-events │ │ └── index.tsx │ ├── shared │ │ ├── hooks │ │ │ ├── useActiveLinks.ts │ │ │ └── useForm.ts │ │ └── utils │ ├── styles │ │ ├── Home.module.css │ │ └── globals.css │ ├── theme │ │ ├── components │ │ ├── foundations │ │ │ ├── colors.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ └── styles.ts │ └── types │ └── index.ts ├── tsconfig.json └── yarn.lock 
/* src/pages/communities/index.ts */ import < NextPage > from "next"; import Head from "next/head"; import < Fragment > from "react"; import < Box, Button, Flex, Heading, VStack, InputGroup, InputLeftElement, Input, HStack, Text, Image, > from "@chakra-ui/react"; import < SearchIcon > from "@chakra-ui/icons"; import AppFooter from "../../components/footer"; // relative paths import NavBar from "../../components/navbar"; // relative paths const Communities: NextPage = () => < // page code >; export default Communities; 

This can get really messy especially when we have deeply nested files.

import somthing from "../../../../../somewhere/something"; 

Configuring Typescript to use absolute paths

To enable Typescript to make use of absolute paths to import modules, first go into your tsconfig.json file.

// tsconfig.json < "compilerOptions": < "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true >, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] > 
// tsconfig.json < "compilerOptions": < "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "baseUrl": "." // here >, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] > 
  • add the paths of the folders you’ll want to be able to reference in the «paths» option, I’ll be adding my «components» , » theme» and » shared» to the path.
// tsconfig.json < "compilerOptions": < "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "baseUrl": ".", // here "paths": < "@component/*": ["./src/component/*"], "@theme/*": ["./src/theme/*"], "@shared/*": ["./src/shared/*"] > >, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] > 

Now we can reference our absolute path using the keys we used to reference it in our code base.

/* src/pages/communities/index.ts */ import < NextPage > from "next"; import Head from "next/head"; import < Fragment > from "react"; import < Box, Button, Flex, Heading, VStack, InputGroup, InputLeftElement, Input, HStack, Text, Image, > from "@chakra-ui/react"; import < SearchIcon > from "@chakra-ui/icons"; import AppFooter from "@components/footer"; // absolute paths import NavBar from "@components/navbar"; // absolute paths const Communities: NextPage = () => < // page code >; export default Communities; 

why use the @ prefix

This is largely a matter of personal preference, and your reference does not have to begin with ‘@’ ; it can simply be the name of your file, or you can call it whatever you want as long as it is an alpha-numeric character or a string that can be a valid JSON key.

Читайте также:  Javascript повторное использование кода

Why use absolute paths

This is a subtle feature, but it can help with code readability and overall cleaner imports.

Conclusion

Typescript is a wonderful programming language with tons of great features. Absolute paths have no effect on your code in runtime; it’s more of a code readability thing. There are other features that do add a lot to your code, such as decorators, enums, abstract classes, and so on. This is only scratching the surface.

Источник

Configuring React Absolute Imports For TypeScript

Are you really tired of typing code like this in your React projects?

import < AppContextProvider >from "../../state/State"; import MyComponent from "../../components/MyComponent/MyComponent"; import "./App.css"; 

Typing those relative paths with directory access dots is cumbersome and confusing. Wouldn’t it be great to just do this?

import < AppContextProvider >from "state/State"; import MyComponent from "components/MyComponent/MyComponent"; import "./App.css"; 

Absolute Imports to the Rescue!

Guess what? You can! Here’s how it works. In a create-react-app project that uses TypeScript, modify your tsconfig.json file to look like this:

Hat tip to Chiamaka Ikeanyi for this suggestion.

Now, restart by doing yarn start or npm run start . Tada! Your absolute path imports work perfectly.

But. (there’s always a but), in Visual Studio Code you’re seeing:

Well, there MIGHT be a really easy fix for that. Just close and then re-open Visual Studio Code. For most people, that will fix the problem. If not, then open your settings and search for import module specifier . You’ll find one for TypeScript > Preferences > Import Module Specifier .

If you change this setting to Auto or Non-relative , Visual Studio Code will understand how to import modules based on your tsconfig.json file. You may need to close and reopen the IDE again for it to take effect.

Absolute Imports with Vanilla JavaScript

Haven’t embraced TypeScript yet? No problem! You can do the same thing with vanilla JavaScript.

NOTE: I haven’t tested this so let me know if it doesn’t work.

If you don’t already have one, add a .env file to your working directory. In it add:

Testing without TypeScript

FYI: The below assumes your are NOT using TypeScript. If you’re just using JS, you’ll need to do the following:

All is great, right? Unfortunately, you just broke all your tests 😢! The problem is that Jest doesn’t know about all this baseUrl magic.

Thanks to Kent C. Dodds and his excellent Testing JavaScript course, there’s a fix for this too!

In your jest.config.js file, do this:

const path = require("path"); module.exports = < . moduleDirectories: ["node_modules", path.join(__dirname, "src")], >; 

Now, rerun your tests and all is well!

Let me know if you have any other suggestions for this via Twitter @Calendee

Источник

Using absolute path import with Typescript + babel + nodemon in Your Node Project

From now, I will show you how to configure each of them. I will suppose to use nodemon in both ways.

0. File Structure

I will suppose the file structure like following:

├─src │├─hello ││ └─abc.ts │└─index.ts ├─.babelrc ├─nodemon.json ├─package.json └─tsconfig.json 

abc.ts and index.ts will be like this:

import abc from 'hello/abc'; console.log(`Hello, $`); 

src/hello/abc.ts

package.json

Some of the packages is not needed by the way you use. You don’t need @babel/preset-typescript if you transpile with tsc like so forth.

1. Typescript-transpile with tsc , then babel-transpile with babel-plugin-module-resolver

First, you can write start script like follow in your package.json .

package.json

and other configuration file like follow:

tsconfig.json

nodemon.json

If you npm start or yarn start , then tsc will transpile your typescript the way you wrote in tsconfig.json . the baseUrl and paths will help resolve your absolute path while tsc transpile. Then, your transpiled code will be run by babel-node . Wile transpiling with babel, you have to specify given absolute path into what babel can understand, so you have to specify the alias in the .babelrc with babel-plugin-module-resolver .

2. Configure .bablerc with @babel/preset-typescript and module-resolver, then transpile your typescript with babel.

You can make similar effect while configuring only .babelrc with @babel/preset-typescript and babel-plugin-module-resolver . You can write path alias information only 1 time in your .babelrc , which is very simple.

First of all, the start script in package.json will be different from the first.

package.json

Then, you have to configure .babelrc and nodemon.json like follow:

nodemon.json

In the code, please focus that alias field in module-resolver : from dist to src . This way only transpiles your code 1 time, so you don’t have to reference tsc-transpiled code path, and you don’t have to define paths in your tsconfig.json . Please be careful with nodemon option —extensions «.ts» that let you transpile your .ts code right a way. If you write ‘.ts’ rather than typing \».ts\» , then the error comes. Be careful.

I prefer the second one because it is simple and capable of using other babel plugins like @babel/plugin-proposal-optional-chaining .

Let’s simplify your path with either way!

Источник

Оцените статью