You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何配置路径,解决同级模块导入找不到的问题?

How to Configure TypeScript to Resolve Local Module Imports Without ./

To fix the "Cannot find module 'Map/map'" error while using non-relative imports (like import { MapProps } from "Map/map"), you’ll need to adjust your TypeScript configuration to recognize local directories as valid module sources. Here’s a step-by-step solution:

1. Update tsconfig.json Core Settings

The key is to tell TypeScript where to resolve non-relative imports from using baseUrl and optionally paths for explicit mapping.

Basic Configuration (baseUrl)

Add baseUrl to your compilerOptions in tsconfig.json. This sets the root directory TypeScript uses to look up non-relative imports. If your tsconfig.json lives in the same folder as map-api.d.ts and the Map directory, set baseUrl to ".":

{
  "compilerOptions": {
    "baseUrl": ".", // Root directory for module resolution
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "NodeNext", // Match your module system (Node.js/ES modules)
    "strict": true // Optional, but recommended for type safety
  },
  "include": [
    "**/*.d.ts",
    "**/*.ts"
  ]
}

With this setup, TypeScript will resolve import { MapProps } from "Map/map" to ./Map/map automatically.

Explicit Path Mapping (Optional)

If you need more control or the basic setup doesn’t work, add a paths entry to explicitly map the Map directory:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "Map/*": ["./Map/*"] // Maps any "Map/" import to the local ./Map/ folder
    },
    // Other compiler options...
  }
}

2. Configure Your Bundler (If Using One)

If you’re using a bundler like Webpack, Vite, or Rollup, you’ll need to mirror this path mapping so the bundler can resolve imports during build time:

For Webpack

Add an alias to webpack.config.js:

const path = require('path');

module.exports = {
  resolve: {
    alias: {
      'Map': path.resolve(__dirname, './Map')
    }
  }
};

For Vite

Add an alias to vite.config.js:

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      'Map': path.resolve(__dirname, './Map')
    }
  }
});

Why This Works

By default, TypeScript treats non-relative imports (without ./ or ../) as packages from node_modules. Setting baseUrl redirects TypeScript to look for these modules in your local project root instead. The paths option adds explicit aliases for specific directories, ensuring consistent resolution across your codebase.

Content of the question来源于stack exchange,提问作者POV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:53:11