导出用JS编写的类module.export如何在javascript的html脚本中使用它?

问题描述

我有一个用Java编写的类。 此类在文件中:Parcours.js。

module.exports = class Parcours {
constructor(componentList) {
    this.components = componentList;
    this.length = componentList.length;
    this.current = 0; // We start at the first component.
}

next () { // my next function
...

我和蔡老师一起上这堂课:

const Parcours = require('../app/Parcours');
const expect = require('chai').expect;

describe('Parcours',() => {
describe('Test empty page list',() => {
    it('Constructor : Empty page list should give a zero length,an empty component list and a current to be zero',() => {
        const parcours = new Parcours([]);
        expect(parcours.length).to.equal(0);
        expect(parcours.current).to.equal(0);
...

效果很好。一切都很好。

现在,我想将此类用于HTML页面。我想将这个类实例化为“ parcours”对象。

为此,首先我有一个div:

<div hidden='true' id='adjustment-panel'>
<input type='submit' id='prevIoUs-ajustment' value='Précédent' onclick='parcours.next()' />
<label for='adjustment'>Ajustement : </label>
...

parcours.next是对Parcours类的parcours实例的“ next”方法调用

我的问题是:我不知道如何

  1. 将Parcours类导入到我的HTML脚本标记
  2. 如何将Parcours类实例化为对象“ parcours”
  3. 如何在DOM事件onclick(或任何其他事件)中使用它

我尝试了什么: 我将类包含在我的身体脚本中:

    <script type='module' src='./app/Parcours.js'></script>
    <script>
        const Etapes = ['player-panel','adjustment-panel','target-panel'];
        const parcours = new Parcours(Etapes);
    </script>

但是结果是:

(index):45 Uncaught ReferenceError: Parcours is not defined at (index):45

其中index:45是我在onclick事件中使用parcours.next()的行:

    <input type='submit' id='prevIoUs-ajustment' value='Précédent' onclick='parcours.next()' />

您能为我提供一个很好的方法吗?

非常感谢

解决方法

找到了!

使用模块ECMASCRIPT 6

我的班级现在在Parcours.mjs文件中展开:

export class Parcours {
    constructor(componentList) {
...

我将其导入到chai文件测试中,这也将成为.mjd文件

import { Parcours } from '../public/scripts/Parcours.mjs';
import pkg from 'chai';
const { expect } = pkg;

describe('Parcours',() => {
...

测试再次正常进行。

而且,在我的HTML文件中,我正确地使用了导入(希望如此):

<script type='module'>
    import { Parcours } from './Parcours.mjs'
    const Etapes = ['player-panel','adjustment-panel','target-panel'];
    window.parcours = new Parcours(Etapes);
</script>

一切正常!

谢谢所有看过它的人!