GatsbyJS:如何在Pages文件夹添加不生成页面的文件?
Gatsby默认会把src/pages下的所有JS/JSX/TS/TSX文件自动生成对应路由的页面,但针对你这种「把组件放在pages子目录下、只作为导入模块不生成页面」的需求,有几个简单好用的解决方案:
方法1:给组件文件加前缀(最简单!)
Gatsby有个内置规则:文件名以_或.开头的文件不会被识别为页面组件。你只需要把contact-form.js改成_contact-form.js或者.contact-form.js,就能让Gatsby自动忽略它,不会生成/contact/contact-form的页面。
修改后你的目录结构变成:
src └── pages └── contact ├── index.js └── _contact-form.js
然后在index.js里正常导入组件就行:
import ContactForm from './_contact-form'; const ContactPage = () => { return ( <div> <h1>联系我们</h1> <ContactForm /> </div> ); }; export default ContactPage;
这种方法零配置,适合单个或少量组件的场景,完全满足你的需求。
方法2:通过gatsby-node.js自定义页面生成逻辑
如果你需要更复杂的控制(比如批量排除某类文件),可以在项目根目录的gatsby-node.js里修改createPages API,过滤掉不想生成页面的文件:
exports.createPages = async ({ actions, graphql }) => { const { createPage } = actions; // 查询所有pages目录下的文件 const queryResult = await graphql(` query { allFile(filter: { sourceInstanceName: { eq: "pages" } }) { nodes { relativePath absolutePath } } } `); // 遍历文件,跳过contact-form.js queryResult.data.allFile.nodes.forEach(node => { if (node.relativePath === 'contact/contact-form.js') { return; // 跳过该文件,不生成页面 } // 对其他文件执行默认的页面生成逻辑 createPage({ path: `/${node.relativePath.replace('.js', '').replace('index', '')}`, component: require.resolve(node.absolutePath), }); }); };
这个方法适合需要自定义路由规则或者批量处理的场景,但需要你熟悉Gatsby的Node API。
方法3:使用gatsby-plugin-page-creator插件配置排除规则
Gatsby的官方插件gatsby-plugin-page-creator可以让你自定义pages目录的文件识别规则,通过ignore选项排除特定文件:
首先确保你安装了这个插件(如果没装的话,运行npm install gatsby-plugin-page-creator或yarn add gatsby-plugin-page-creator),然后在gatsby-config.js里配置:
module.exports = { plugins: [ { resolve: `gatsby-plugin-page-creator`, options: { path: `${__dirname}/src/pages`, // 排除contact目录下的contact-form.js文件 ignore: [`**/contact/contact-form.js`], }, }, ], };
这种方法适合需要统一管理页面生成规则的场景,配置一次后可以轻松添加更多排除项。
总结一下,你的场景里方法1是最快捷的解决方案,只需要修改文件名前缀就能搞定,完全不需要额外配置~
内容的提问来源于stack exchange,提问作者Moshe

