Javascript “什么是”呢;导出默认类渲染";在本代码中,为什么要导出并使用它?

Javascript “什么是”呢;导出默认类渲染";在本代码中,为什么要导出并使用它?,javascript,typescript,electron,Javascript,Typescript,Electron,这是我第一次尝试从具有django背景的C/C++/Python创建一个电子应用程序,但我不太了解这段代码中发生了什么。这是这里的回购协议 为什么要导出同一脚本文件中使用的类? 这是对电子的某种要求吗 import * as BABYLON from 'babylonjs'; export default class Renderer { private _canvas: HTMLCanvasElement; private _engine: BABYLON.Engine;

这是我第一次尝试从具有django背景的C/C++/Python创建一个电子应用程序,但我不太了解这段代码中发生了什么。这是这里的回购协议

为什么要导出同一脚本文件中使用的类? 这是对电子的某种要求吗

import * as BABYLON from 'babylonjs';

export default class Renderer {
    private _canvas: HTMLCanvasElement;
    private _engine: BABYLON.Engine;
    private _scene: BABYLON.Scene;

    createScene(canvas: HTMLCanvasElement, engine: BABYLON.Engine) {
        this._canvas = canvas;

        this._engine = engine;

        // This creates a basic Babylon Scene object (non-mesh)
        const scene = new BABYLON.Scene(engine);
        this._scene = scene;

        // This creates and positions a free camera (non-mesh)
        const camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);

        // This targets the camera to scene origin
        camera.setTarget(BABYLON.Vector3.Zero());

        // This attaches the camera to the canvas
        camera.attachControl(canvas, true);

        // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
        const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);

        // Default intensity is 1. Let's dim the light a small amount
        light.intensity = 0.7;

        // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
        const sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);

        // Move the sphere upward 1/2 its height
        sphere.position.y = 1;

        // Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
        const ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);
    }

    initialize(canvas: HTMLCanvasElement) {
        const engine = new BABYLON.Engine(canvas, true);
        this.createScene(canvas, engine);

        engine.runRenderLoop(() => {
            this._scene.render();
        });

        window.addEventListener('resize', function () {
            engine.resize();
        });
    }
}

const renderer = new Renderer();
renderer.initialize(document.getElementById('render-canvas') as HTMLCanvasElement);

当您在同一文件上时,可以使用不带导出的类。然而,添加导出的目的是在导入的帮助下由其他程序重用代码

导出有两种类型,一种是命名导出,另一种是默认导出

在您的示例中,您使用了默认导出。默认导出对于导出单个对象、函数或变量非常有用。您可以在导入时使用任何名称

就像您的情况一样,您可以导入

import Render from './renderer';
这里我假设您将此文件保存在renderer.js文件中。您可以看到,当我导入时,我使用不同的名称作为渲染器而不是渲染器。我之所以能够这样做,是因为类使用了默认的导出


要了解更多信息,请单击

可能不需要。它可能是一个从未使用过的冗余输出。或者其他地方的代码也需要这个类?正如@dwjohnston所说,这里并没有什么特别的,这个类被导出只是因为其他文件可以导入它。如果没有文件导入此类,则无需添加export语句。