首页 > 解决方案 > 来自两个不同 JS 文件的交叉引用数据

问题描述

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

import { Boid } from './boid';

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

boid.js我定义了一个对对象Boid执行方法的类cmain.js

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

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

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

你可以在https://github.com/michaelmoreno/boids-algorithm自己查看我的仓库

标签: javascriptimportexportbundlerrollup

解决方案


用这个:

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

然后:

   window.c.beginPath()

推荐阅读