【发布时间】:2021-06-10 17:38:10
【问题描述】:
我刚刚创建了一个新的 Gatsby 项目,并创建了几个小组件,这些组件在导入后会显示在索引页面上,如下所示:
import Nav from "../components/Nav"
import Intro from "../components/Intro"
import About from "../components/About"
import Experience from "../components/Experience"
import Projects from "../components/Projects"
import Contact from "../components/Contact"
import Footer from "../components/Footer"
想要稍微整理一下,我发现您可以使用 webpack 定义别名并安装 gatsby-plugin-alias-imports 来实现这一点。使用yarn add gatsby-plugin-alias-imports 安装插件并添加必要的配置后,我的gatsby-config.js 如下所示:
const path = require('path')
module.exports = {
siteMetadata: {
title: "Site Title",
},
plugins: [
{
resolve: "gatsby-plugin-alias-imports",
options: {
alias: {
'@components': path.resolve(__dirname, 'src/components'),
'@pages': path.resolve(__dirname, 'src/pages'),
},
extensions: [
"js",
],
}
},
...
...
我的项目结构如下:
.
├── README.md
├── gatsby-config.js
├── package.json
├── src
│ ├── components
│ │ ├── about.js
│ │ ├── contact.js
│ │ ├── experience.js
│ │ ├── footer.js
│ │ ├── intro.js
│ │ ├── nav.js
│ │ └── projects.js
│ ├── pages
│ │ ├── 404.js
│ │ └── index.js
│ └── scss
│ └── main.scss
├── static
│ └── static
│ └── icons
│ ├── github.svg
│ ├── instagram.svg
│ └── linkedin-in.svg
└── yarn.lock
然而,每当我尝试在导入中使用 @components 语法时:
import { Nav, Intro, About, Experience, Projects, Contact, Footer } from "@components"
yarn run develop 报告无法解析 @components 别名:
ERROR #98124 WEBPACK
Generating development SSR bundle failed
Can't resolve '@components' in '/Users/James/Projects/personal-site/src/pages'
If you're trying to use a package make sure that '@components' is installed. If you're trying to use a
local file make sure that the path is correct.
File: src/pages/index.js:2:0
我是否遗漏了一些明显的东西?我已经阅读了该插件的文档,并且认为我没有遗漏任何内容。我已经对node_modules 和yarn.lock 进行了核对,但没有成功。
有人有什么建议吗?
【问题讨论】:
标签: javascript node.js reactjs webpack gatsby