Import - Avoid Using Absolute Paths in Imports
What is it?
This practice warns against using absolute paths when importing modules in TypeScript. Absolute paths tie your code to a specific file system layout, which can hinder portability and cause issues when distributing your code, for example via NPM packages.
Why apply it?
Using absolute paths limits the flexibility and reusability of your code. When you use relative paths or proper module names instead, your imports remain valid regardless of the file system structure, making your code easier to maintain, share, and deploy across different environments.
How to Fix it?
Replace absolute paths in your import statements with paths relative to the current file or appropriate module names. This adjustment not only minimizes system-specific dependencies but also improves your project's portability and compatibility.
Examples
Example 1:
Positive
Correct implementation following the practice.
import { helperFunction } from '../api/helper';
function performTask(): void {
console.log("Starting task...");
helperFunction();
console.log("Task finished.");
}
performTask();
Negative
Incorrect implementation that violates the practice.
import config from '/usr/local/project/config/settings';
class Server {
private config: any;
constructor() {
this.config = config;
console.log("Configuration loaded successfully.");
}
start(): void {
console.log("Server started on port", this.config.port);
}
}
const app = new Server();
app.start();
Example 2:
Positive
Correct implementation following the practice.
import config from './config/settings';
class Server {
private config: any;
constructor() {
this.config = config;
console.log("Configuration loaded successfully.");
}
start(): void {
console.log("Server started on port", this.config.port);
}
}
const app = new Server();
app.start();
Negative
Incorrect implementation that violates the practice.
import { helperFunction } from '/home/project/api/helper';
function performTask(): void {
console.log("Starting task...");
helperFunction();
console.log("Task finished.");
}
performTask();