Angular中如何配置路径,解决同级模块导入找不到的问题?
./ 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

