Gatsby配置gatsby-plugin-root-import后Storybook绝对路径报错如何解决?
问题本质
gatsby-plugin-root-import 只会修改Gatsby内置的webpack解析规则,Storybook使用独立的webpack配置,不会自动同步别名规则,需要手动对齐配置。
步骤1:修改Storybook main.js的webpack配置
找到Storybook配置目录下的main.js,修改webpackFinal字段,添加和Gatsby侧完全一致的路径别名与模块解析规则:
const path = require('path') webpackFinal: async config => { // 原有配置保留 config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/] config.module.rules[0].use[0].options.plugins.push( require.resolve("babel-plugin-remove-graphql-queries") ) // 新增绝对路径解析规则,和gatsby-plugin-root-import配置保持一致 config.resolve = config.resolve || {} config.resolve.alias = { ...config.resolve.alias, // 对应你Gatsby配置里的utils别名 utils: path.resolve(__dirname, '../src/components/utilities') } config.resolve.modules = [ ...(config.resolve.modules || []), // 对应你Gatsby配置里的resolveModules配置 path.resolve(__dirname, '../libs') ] return config },
注意:上面的路径根据你的Storybook配置文件存放位置调整,默认Storybook配置放在项目根目录的.storybook文件夹下,所以../对应项目根目录,如果你存放位置不同需要修改相对路径。
步骤2:修改tsconfig.json匹配别名规则
打开tsconfig.json,取消baseUrl的注释,新增paths字段匹配别名:
{ "compilerOptions": { "baseUrl": "src", "target": "esnext", "module": "esnext", "lib": ["dom", "es2017"], "jsx": "react", "strict": true, "esModuleInterop": true, "moduleResolution": "node", "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true, "skipLibCheck": true, // 新增paths配置对齐别名 "paths": { "utils/*": ["components/utilities/*"] } }, "exclude": ["node_modules"], "include": ["**/*.ts", "**/*.tsx"] }
改完重启Storybook即可生效,绝对路径导入不会再报错。
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

