React+Storybook遇TS2307:找不到'Button'模块,能否解决?
Let's break down why this is happening and how to fix it step by step.
First, the core issue: Storybook doesn't automatically inherit all your project's TypeScript/path resolution settings out of the box. While your Create React App setup recognizes the absolute path 'Button', Storybook's build process needs explicit configuration to map that alias to the actual component file.
Step 1: Fix your project's tsconfig.json
Your current paths configuration maps src/* to ./src/*, but you're trying to import directly from 'Button' (not 'src/Button'). Let's adjust the paths to match your import pattern, and also make sure we're including JS files since your components are .js:
{ "compilerOptions": { "jsx": "react", "esModuleInterop": true, "moduleResolution": "node", "strictNullChecks": true, "rootDir": "src", "baseUrl": "./", "paths": { "Button": ["./src/Button/Button.js"], "Button/*": ["./src/Button/*"] } }, "include": [ "./src", "./src/**/*.ts", "./src/**/*.tsx", "./src/**/*.js", "./src/**/*.jsx" ] }
If you want to make this more scalable (so you can import other components with absolute paths too), you could use a wildcard instead:
"paths": { "*": ["./src/*"] }
This would let you import any component in src like import { X } from 'X'.
Step 2: Configure Storybook to resolve the alias
Storybook uses its own webpack config, so we need to tell it about the Button alias. Create or edit .storybook/main.js (or .ts if you're using TypeScript for config) with these changes:
const path = require('path'); module.exports = { stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], addons: ['@storybook/addon-links', '@storybook/addon-essentials', '@storybook/preset-create-react-app'], // Tell Storybook to use our project's tsconfig typescript: { reactDocgen: 'react-docgen-typescript', reactDocgenTypescriptOptions: { tsconfigPath: '../tsconfig.json', }, }, // Update webpack to resolve the alias webpackFinal: async (config) => { config.resolve.alias = { ...config.resolve.alias, 'Button': path.resolve(__dirname, '../src/Button/Button.js'), // If you used the wildcard paths config above, replace the line above with: // '*': path.resolve(__dirname, '../src/*'), }; return config; }, };
Step 3: Restart your Storybook server
Changes to config files won't take effect until you stop and restart the Storybook dev server. Run npm run storybook (or your equivalent command) again, and the TS2307 error should be gone.
Quick Notes
- If you're using TypeScript for your components later, make sure you have a
Button.d.tsfile in theButtonfolder to defineButtonPropsproperly, since right now you're importing it from a.jsfile. - The
@storybook/preset-create-react-apphelps align Storybook with CRA's settings, but it doesn't handle custom path aliases automatically—hence the need for the webpack alias config.
内容的提问来源于stack exchange,提问作者anyapps

