React/TypeScript/webpack项目如何用相对路径正确导入TSX文件?
Hey there! Let's break down why your LESS imports work smoothly but TSX files require full paths or aliases to compile. This is almost always a configuration mismatch between webpack and TypeScript when resolving file extensions and module paths. Here's how to fix it:
1. Update Webpack's Resolve Extensions
Webpack uses the resolve.extensions array to automatically look for files without needing full extensions. If .tsx isn't in this list, webpack won't recognize your shorthand imports for TSX components.
Add .tsx to the top of the extensions list in your webpack.config.js (order matters—webpack checks extensions in the given sequence):
module.exports = { // ... other webpack config resolve: { extensions: ['.tsx', '.ts', '.js', '.less'], }, };
This tells webpack to first look for .tsx files when you write import { TestComponent } from './TestComponent', then .ts, etc.
2. Align TypeScript Configuration
TypeScript needs to know which file extensions to resolve too, otherwise your IDE might throw errors even if webpack compiles successfully. Update your tsconfig.json:
{ "compilerOptions": { "baseUrl": "./src", // Set this to your source code root (e.g., src/) "moduleResolution": "node", // Matches Node.js module resolution behavior "extensions": [".tsx", ".ts", ".js"], // Match webpack's extension order "paths": { "@src/*": ["*"] // If you want to keep using the @src alias } }, "include": ["src/**/*"] // Ensure all your source files are included }
baseUrllets TypeScript resolve relative paths from your source root.moduleResolution: "node"ensures TS uses the same resolution logic as webpack and Node.js.- The
pathsentry maintains your existing@srcalias if you prefer using that over relative paths.
3. Verify Consistency Between Configs
Make sure webpack's resolve.alias (if you use it) matches TypeScript's paths configuration. For example, if webpack has:
resolve: { alias: { '@src': path.resolve(__dirname, 'src'), }, }
Your tsconfig's paths should mirror this to avoid IDE errors.
Why LESS Files Work Without Issues?
Webpack's less-loader is set up to handle .less files by default, and .less is likely already in your resolve.extensions array. That's why import './styles.less' works without extra configuration.
After making these changes, you'll be able to use both shorthand relative imports:
import './styles.less'; import { TestComponent } from './TestComponent'; // No .tsx suffix needed!
Or your preferred alias syntax:
import { TestComponent } from '@src/components/TestComponent';
内容的提问来源于stack exchange,提问作者Scott Schafer




