首页 > 解决方案 > 如何在 reactjs 组件中使用使用 scalajs 导出的函数?

问题描述

我尝试main.js使用@JSExportTopLevel注释将一些函数导出到 scalajs 中的文件,如Export Scala.js APIs to JavaScript scalajs 文档中所述,并main.js按照此处所述构建。

这导致main.js我可以使用在 scalajs 代码中导出的函数。

现在我想在我的 reactjs 组件中使用这些导出的函数。为此,我尝试了以下步骤:

  1. 复制main.js文件public夹中的文件
  2. 在 中包含 javascript 文件index.html,如下所示:
<script type="text/javascript" src="./main.js"></script>

现在,如果我在浏览器中加载应用程序并尝试在浏览器控制台中使用这些功能,它可以正常工作:

console.log(foo());

但我不是在 reactjs 组件中使用这些功能:

import React from 'react';

const RuleEditor = () => {

    console.log(foo());

    return (
        <>
        </>
    );
};

export default RuleEditor;

我总是收到以下编译错误:

foo is not defined  no-undef

我确实理解 reactjs 无法识别该功能,因为我还没有真正指定从哪里获取该功能,但我不确定如何实现它。我已经看过其他几个 stackoverflow 帖子,其中一些建议在window对象中查找它,但我没有在那里找到这些函数。

请提出一种正确的方法来使用从 scalajs 导出的函数在 reactjs 组件中。TIA。

标签: javascriptreactjsscala.js

解决方案


将对象/类/函数导出为顶级导出将它们置于 Javascript 全局范围内。

class Foo(val x: Int) {
  @JSExport
  def square(): Int = x*x // note the (), omitting them has a different behavior
  @JSExport("foobar")
  def add(y: Int): Int = x+y
}

您可以在嵌入在 html 或 scalajs 中的脚本中使用这些函数,如此处所示。

但是如果您需要在 nodejs 应用程序中使用这些功能,则需要从模块中导出这些功能。我们需要在build.sbt. 在这里阅读更多。

scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) }

现在,我们可以通过像这样导入它们来在 nodejs 应用程序中使用导出的函数:

import { square, add } from './main'

如果您希望从名为 以外的模块导出这些函数main,请为每个导出的函数提供模块 ID,如下所示:

class Foo(val x: Int) {
  @JSExport("square", "my-math")
  def square(): Int = x*x // note the (), omitting them has a different behavior
  @JSExport("foobar", "my-math")
  def add(y: Int): Int = x+y
}

并像这样使用它:

import { square, add } from './my-math'

推荐阅读