如何在NextJS项目中引用外部/common目录下的公共.ts文件?
如何在Next.js项目中引用外部公共目录的文件
针对你的目录结构,要在/root/src/app/page.tsx里引用/common下的文件,可以通过两种方式实现:
方式一:配置路径别名
1. 修改tsconfig.json
在/root/tsconfig.json的compilerOptions中添加路径映射,同时确保公共目录被TypeScript识别:
{ "compilerOptions": { "baseUrl": ".", "paths": { "@common/*": ["../common/*"] }, // 保留原有其他配置 }, "include": ["src/**/*", "../common/**/*"] }
2. 配置Next.js构建工具
在/root/next.config.js中添加webpack别名配置,让Next.js的打包工具能解析这个路径:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.resolve.alias['@common'] = require('path').resolve(__dirname, '../common'); return config; }, }; module.exports = nextConfig;
3. 在page.tsx中引用
完成配置后,直接通过别名导入公共文件:
import { /* 你需要的导出内容 */ } from '@common/common1'; export default function Home() { return ( <main> {/* 使用公共文件中的内容 */} </main> ); }
方式二:将公共目录转为本地npm包(更适合多项目共享)
如果要给多个Next.js项目共享/common,把它做成本地私有包更方便:
- 在
/common目录下执行npm init,创建package.json,设置name为@your-name/common,并加上"private": true(避免误发布到npm) - 在每个Next.js项目的
/root/package.json中添加依赖:"dependencies": { "@your-name/common": "file:../common" } - 执行
npm install后,就可以像引用第三方包一样导入:import { /* 导出内容 */ } from '@your-name/common/common1';
内容的提问来源于stack exchange,提问作者Sylv99
相关产品推荐
相关产品推荐

