サムネイル

Next.jsでvcfファイルダウンロードボタンを作ってみた。(Safari対応)

今回はNext.jsでvcfファイルをダウンロードするボタンを作ってみたので、是非参考にしてみてください。

環境

  • next: 14.0.4
  • react: ^18
  • typescript: ^5

vcfファイルとは

連絡先とその関連情報を保存する仮想連絡先ファイルです。 VCF ファイルは vCard ファイルとしても知られ、電話番号、住所、連絡先の写真、Web サイトのアドレス、電子メール ID などの連絡先情報を保存するための設計されたフィールドで構成されます。

https://www.msoutlooktools.com/jp/open-vcf-file-on-computer/

モジュールをインストールする

https://www.npmjs.com/package/vcards-js

$ npm i vcards-js

vcfファイルをダウンロードさせるボタンの作成

まずは普通のボタンを作ります。

const VcfDownloadBtn = () => {
  return (
    <button type="button">ダウンロード</button>
  )
}

ここにダウンロードボタンを押したら、vcfファイルをダウンロードをさせる処理を書いていきます。

const VcfDownloadBtn = () => {
  const CreateVCard = (
    firstName = "",
    lastName = "",
    organization = "",
    postalCode = "",
    street = "",
    homePhone = "",
    homeFax = "",
    email?: string,
    url = "",
    note = ""
  ): string => {
    const vCardsJS = require("vcards-js");
    const vCard = vCardsJS();

    vCard.firstName = firstName;
    vCard.lastName = lastName;
    vCard.organization = organization;
    vCard.homeAddress.postalCode = postalCode;
    vCard.homeAddress.street = street;
    vCard.homePhone = homePhone;
    vCard.homeFax = homeFax;
    vCard.email = email;
    vCard.url = url;
    vCard.note = note;

    return vCard.getFormattedString();
  };

  const handleClick = (vcfText: string) => {
    const element = document.createElement("a");
    const file = new Blob([vcfText], { type: "text/vcard;charset=utf-8" });
    element.href = URL.createObjectURL(file);
    element.download = "myFile.vcf";
    document.body.appendChild(element);
    element.click();
  };
  return (
    <button 
      type="button"
      onClick={() =>
            handleClick(
              CreateVCard(
                "山田",
                "太郎",
                "WEBエンジニア",
                "999-9999",
                "バーリント西区公園通り128",
                "99-9999-9999",
                "00-0000-0000",
                "hoge@xxx.xx",
                "https://xxxxx.xxxxxx",
                "架空の人物です。"
              )
            )
          }
     >ダウンロード</button>
  )
}

以上で完成なのですがこのままだと下記エラーが出ます。

Module not found: Can't resolve 'fs'

対処法として、next.config.jsに以下を追加してください。

webpack: (config) => {
  config.resolve.fallback = { fs: false };
  return config;
},

これでエラーが無くなり、無事vcfファイルがダウンロードされると思います。

詳しくはドキュメントをチェックしてください。
https://github.com/enesser/vCards-JS