LoginSignup
0
0

More than 1 year has passed since last update.

【js-yaml】カスタムタグを追加する【Node.js】

Last updated at Posted at 2022-11-09

最初に

yamlファイルでカスタムタグを使用している場合は、loadする際にその型情報を定義しないとエラーになります。

  • カスタムタグを使ったyamlの例
'---\n test: !NewCustomType\n'
  • エラー例:
"errorMessage":"YAMLException: unknown tag !<NewCustomType>

定義のしかたを知ったのでメモしておきます。

🌱 環境

  • node: v16.17.0
  • js-yaml: 4.1.0

結論

定義するにはshcemaというオプションに型情報を渡せばよさそうです。

const yaml = require('js-yaml')
const customType = new yaml.Type(
  '!NewCustomType',  // ここに使用するカスタムタグ名を定義
  { kind: 'mapping' }
)
const customSchema = yaml.DEFAULT_SCHEMA.extend([customType])
yaml.load('path/to/yamlfile', {schema: customSchema}) // ここで定義したschemaオプションをつける

補足
stackoverflowなどでschemaの設定方法を探すとDEFAULT_SCHEMA.extend()ではなくyaml.Schema.create()を使っているものが出てきますが、Schema.create()はもう使用できないみたいでした。
参考: TypeError: yaml.Schema.create is not a function

参考

参考にさせていただきました

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0