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

如何在Next.js 14(App Router)中配置BALKAN FamilyTreeJS

解决Next.js 14(App Router)集成@balkangraph/familytree.js的配置问题

一、修复next.config.js模块解析错误

Next.js 14默认支持ES模块配置,无需使用require,按以下步骤调整:

  • 将next.config.js重命名为next.config.mjs,采用ES模块语法编写配置。
  • 替换过时的next-transpile-modules,改用Next.js内置的transpilePackages属性转译第三方包,配置示例:
/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['@balkangraph/familytree.js'],
  // 保留你的其他Next.js配置
}

export default nextConfig

二、解决Tailwind CSS与包的样式冲突

  1. 更新Tailwind内容配置:在tailwind.config.js中添加包的文件路径,确保Tailwind能正确解析包内的样式依赖:
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './node_modules/@balkangraph/familytree.js/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
  // 可选:禁用Tailwind预飞行样式,避免与包自带样式冲突
  corePlugins: {
    preflight: false,
  },
}
  1. 调整样式导入顺序:在全局样式文件(如app/globals.css)中,先导入包的CSS,再导入Tailwind指令,确保样式优先级符合预期:
@import '@balkangraph/familytree.js/dist/familytree.css';

@tailwind base;
@tailwind components;
@tailwind utilities;

三、解决"Module parse failed: Unexpected character '@'"错误

该错误源于包内非JS/TS文件未被正确转译,除上述transpilePackages配置外,补充webpack规则处理:

  • 在next.config.mjs中添加webpack配置,专门处理包内的CSS文件:
/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['@balkangraph/familytree.js'],
  webpack: (config) => {
    config.module.rules.push({
      test: /\.css$/,
      include: /node_modules\/@balkangraph\/familytree.js/,
      use: ['style-loader', 'css-loader'],
    });
    return config;
  },
}

export default nextConfig
  • 执行命令安装依赖:npm install style-loader css-loader --save-dev

四、客户端组件中正确使用包

由于@balkangraph/familytree.js依赖DOM环境,需在客户端组件中使用,添加'use client'指令:

'use client';

import { useEffect, useRef } from 'react';
import { FamilyTree } from '@balkangraph/familytree.js';

export default function FamilyTreeComponent() {
  const treeContainer = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!treeContainer.current) return;

    const treeInstance = new FamilyTree(treeContainer.current, {
      nodeBinding: {
        field_0: 'name',
        field_1: 'title',
      },
      nodes: [
        { id: 1, name: 'John Doe', title: 'Father' },
        { id: 2, name: 'Jane Doe', title: 'Mother', parent: 1 },
      ],
    });

    return () => treeInstance.destroy();
  }, []);

  return <div ref={treeContainer} className="w-full h-[600px]"></div>;
}

在App Router页面中直接导入该组件即可使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:43:14