You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不破坏Next.js 14目录结构的前提下创建NPM包?

利用Next.js 14打包器构建可复用NPM包解决方案

1. 调整项目基础配置

首先修改包项目的package.json,明确导出规则与打包入口:

{
  "name": "your-package-name",
  "type": "module",
  "main": "./dist/index.js",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts", // 仅TypeScript项目需要
  "exports": {
    ".": "./dist/index.js",
    "./components": "./dist/components/index.js",
    "./utils": "./dist/utils/index.js"
  },
  "scripts": {
    "build": "next build && next export"
  }
}

2. 配置Next.js为库打包模式

修改next.config.js,禁用不必要的应用特性,专注于模块打包:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  distDir: 'dist',
  experimental: {
    outputFileTracing: false, // 减少冗余依赖打包
  },
  pageExtensions: ['mdx'], // 禁用默认页面路由(若无需页面)
}

module.exports = nextConfig

3. 整理导出模块结构

  • 将需要复用的组件、工具函数放在src/components、src/utils等目录下
  • 在src/index.js(或.ts)中统一导出核心模块:
// src/index.js
export * from './components/Button';
export * from './utils/formatDate';
  • 若要导出整个文件夹,比如所有组件,在src/components/index.js中导出目录内所有文件,再通过根index.js中转:
// src/components/index.js
export { default as Button } from './Button';
export { default as Card } from './Card';

4. 打包生成可发布文件

运行打包命令,Next.js会将编译后的模块输出到dist目录:

npm run build

5. 本地测试(替代npm link)

由于Next.js对符号链接的兼容性问题,推荐用本地包安装替代npm link:

  1. 在包项目根目录执行:
npm pack

这会生成一个your-package-name-x.x.x.tgz压缩包
2. 在测试用的Next.js项目中安装本地包:

npm install ../path/to/your-package/your-package-name-x.x.x.tgz
  1. 在测试项目中导入使用:
import { Button, formatDate } from 'your-package-name';
// 或导入整个组件目录
import { Button, Card } from 'your-package-name/components';

常见问题排查

  • 确保包项目package.json的name字段与测试项目导入的名称一致
  • 若导入报错,检查dist目录结构是否与exports字段配置的路径匹配
  • TypeScript项目需确保tsconfig.json中开启declaration: true,生成类型声明文件
  • 测试时可禁用Next.js缓存:npm run dev --no-cache

内容的提问来源于stack exchange,提问作者Munir Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:55:11