【问题标题】:Cross-reference data from two different JS files来自两个不同 JS 文件的交叉引用数据
【发布时间】:2021-04-17 13:17:14
【问题描述】:

main.js 中我声明了一个画布上下文变量c

import { Boid } from './boid';

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');

boid.js 中,我定义了一个Boid 类,它对来自main.jsc 对象执行方法

export class Boid {
  constructor(pos, vel, accel) {
    this.pos = pos
    this.vel = vel
    this.accel = accel;
  }
  draw() {
    c.beginPath();
  }
}

当我在 chrome 中查看运行站点时,控制台日志

boid.js:8 Uncaught ReferenceError: c is not defined
    at e.draw (boid.js:8)
    at t (main.js:23)
    at main.js:29
    at main.js:29

显然,模块化无法正常工作。我的问题是如何在main.js 中使用来自boid.js 的变量,并在boid.js 中使用来自main.js 的变量,最好不必分别导入/导出它们。

我将 Rollup 用作捆绑程序,因此我只在 index.html 中链接一个缩小的 js 文件,因此不能将 boid.js 链接到 main.js 之上。

你可以在https://github.com/michaelmoreno/boids-algorithm查看我的回购

【问题讨论】:

  • 你应该传递c作为构造函数参数

标签: javascript import export bundler rollup


【解决方案1】:

使用这个:

   window.c = canvas.getContext('2d')

然后:

   window.c.beginPath()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多