JavaScript 我不知道如何把一个 js 模块引入到 importmap 里,帮帮忙吧~

syutran · January 05, 2022 · Last by syutran replied at January 06, 2022 · 537 hits

说好不用 jquery,就坚决不用 jquery。

dabeng/orgchart.js 是这个的:https://github.com/dabeng/OrgChart.js/blob/master/src/orgchart.js

export default class OrgChart {
  constructor(options) {
    this._name = 'OrgChart';
    Promise.prototype.finally = function (callback) {
      let P = this.constructor;

      return this.then(
        value => P.resolve(callback()).then(() => value),
        reason => P.resolve(callback()).then(() => { throw reason; })
      );
    };

    let that = this,
      defaultOptions = {

那该用 importmaps 怎么引用呢?

无论我使用 pin_from_all "app/javascript/src/orgchart.js"

还是 在 application.js 中 import "./src/orgchart"

都无法使用它。

<div id="chart-container">
abcd
</div>

<script>

let datascource = {
  'name': 'Lao Lao',
  'title': 'general manager',
  'children': [
    { 'name': 'Bo Miao', 'title': 'department manager' },
    { 'name': 'Su Miao', 'title': 'department manager',
      'children': [
        { 'name': 'Tie Hua', 'title': 'senior engineer' },
        { 'name': 'Hei Hei', 'title': 'senior engineer',
          'children': [
            { 'name': 'Pang Pang', 'title': 'engineer' },
            { 'name': 'Xiang Xiang', 'title': 'UE engineer' }
          ]
        }
      ]
    },
    { 'name': 'Yu Jie', 'title': 'department manager' },
    { 'name': 'Yu Li', 'title': 'department manager' },
    { 'name': 'Hong Miao', 'title': 'department manager' },
    { 'name': 'Yu Wei', 'title': 'department manager' },
    { 'name': 'Chun Miao', 'title': 'department manager' },
    { 'name': 'Yu Tie', 'title': 'department manager' }
  ]
},
orgchart = new OrgChart({
  'chartContainer': '#chart-container',
  'data' : datascource,
  'depth': 2,
  'nodeContent': 'title'
});

</script>

一直报错:Uncaught ReferenceError: OrgChart is not defined

求大佬 给指点一下,使用 importmaps 作为 rails 的 js,如何引入 ES6 模块,我的问题出在哪儿呢?

如果直接在页面里引用,把模块里的 export default删除,就能用了。

 <script src="http://192.168.3.136:3000/orgchart.js"></script>
 export default 删除是没问题的正常能用

尝试过的方法:

  • import { orgchart } from "./src/orgchart"
  • import orgchart from "./src/orgchart"

import { orgchart } import "./src/orgchart"

不能写两个 import 吧

是我写错了,应该是 from

es module 是有作用域的,哪个地方 import 只会在当前作用域有效。你可以:

1) 在 application 里 import 之后挂到全局变量 window

import OrgChart from "./src/orgchart"

window.OrgChart = OrgChart

2) 在页面内 import

<script type="module">
import OrgChart from "./src/orgchart" 

orgchart = new OrgChart({
  ///
})
</script>
You need to Sign in before reply, if you don't have an account, please Sign up first.