如何在gatsby-plugin-image的StaticImage组件中使用绝对路径引入静态图片
解决方案
方法1:使用gatsby-plugin-root-import插件(最简方案)
- 安装插件
npm install gatsby-plugin-root-import --save # 或使用yarn yarn add gatsby-plugin-root-import
- 修改项目根目录下的
gatsby-config.js配置,将src目录设为路径根目录:
module.exports = { plugins: [ // 原有插件全部保留,比如gatsby-plugin-image、gatsby-plugin-sharp等不要删除 { resolve: `gatsby-plugin-root-import`, options: { src: `${__dirname}/src/` } } ] }
- 重启Gatsby开发服务,之后就可以直接用
src/images/image.png的写法传入StaticImage的src属性。
方法2:手动配置Babel路径别名(无需额外安装Gatsby插件)
如果你不想新增Gatsby插件,可以直接配置Babel的路径解析规则:
- 在项目根目录创建或修改
babel.config.js:
module.exports = { presets: [`babel-preset-gatsby`], plugins: [ [ `module-resolver`, { root: [`./src`], alias: { "src": `./src` } } ] ] }
- 重启Gatsby开发服务即可生效。
注意事项
StaticImage本身的构建时静态解析限制仍然存在,src属性必须直接写静态字符串,不能使用运行时拼接的变量。- 配置修改后必须重启开发服务,否则新的路径规则不会生效。
内容的提问来源于stack exchange,提问作者xy2_
相关产品推荐
相关产品推荐

