Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

dataset-config

ajiho149MIT1.0.0

Parse HTML data attributes into a structured object with automatic type conversion.

data-parser, attribute-parser, data-to-object, dom-data, data-conversion, type-parsing, data-extraction, prefix-filter, exclude-keys, camelcase, deep-object, html-data, data-utils, dataset, data attribute, data attributes, data attrs, HTML element

readme

dataset-config

Buy me a coffee npm cdn version codecov Test


遵循 dataset规范 从dom上提取属性并提供了一些有用的额外功能

[!NOTE] 如果您在开发js插件时,想支持通过data-*属性的方式初始化和传递参数,那么这个库对您来说尤其有用

特性

  • 支持 true/false/number/JSON 解析
  • 支持前缀过滤
  • 支持无限层点语法对象解析
  • 支持全局函数解析
  • 支持排除字段

安装

  • npm: npm install dataset-config --save
  • CDN
    <script src="https://unpkg.com/dataset-config@latest/dist/dataset-config.browser.min.js"></script>
    <!-- or -->
    <script src="https://cdn.jsdelivr.net/npm/dataset-config@latest/dist/dataset-config.browser.min.js"></script>

用法

<div
  data-toggle="plugin"
  data-touch-delay="300"
  data-style.z-index="10000"
  data-position.x="100"
  data-position.y="200"
  data-draggable="true"
  data-direction="horizontal"
  data-app-max-items="5"
  data-app-other-something="should-ignore"
  data-options='{"a":1,"b":[2,3]}'
  data-rect="[2,3]"
  data-config.foo.bar="hello"
  data-on-init="init"
></div>

<script>
  function init() {}

  const el = document.querySelector("[data-toggle]")

  let config = datasetConfig(el, options)

  // config最终的结果会被转换为如下形式:
  config = {
    toggle: "plugin",
    touchDelay: 300,
    style: {
      zIndex: 10000,
    },
    position: {
      x: 100,
      y: 200,
    },
    draggable: true,
    onInit: func,
    direction: "horizontal",
    appMaxItems: 5,
    appOtherSomething: "should-ignore",
    options: {
      a: 1,
      b: [2, 3],
    },
    rect: [2, 3],
    config: {
      foo: {
        bar: "hello",
      },
    },
  }
</script>

选项

prefix

有时候您想避免冲突您可以加一个前缀用以区分

let config = datasetConfig(el, {
  prefix: "app",
})

parseFunction

是否需要解析全局函数,默认为true

excludeKeys

排除某些key不会被解析,默认值为:[]

浏览器支持

具体可以查看.browserslistrc文件。

变更日志

每个版本的详细更改记录在CHANGELOG.md中.

License

MIT

Copyright (c) 2025-present, ajiho

changelog

1.0.0 (2025-05-17)