如何将 dart 编译为 js 以用于非 Web 目标?

问题描述 投票:0回答:2

我想将 dart 编译为 js 以用于非 Web 目标(例如 fermyon/js

node

如何将 dart 编译为 js 以用于非 Web 目标?

更新:

我被告知这是可能的,虽然我找不到任何具体的文档
似乎有两种可能的方法:

这里是使用

js
ts

的基本/示例代码 也可在此示例存储库

中找到
  • 设置节点依赖关系
npm init -y && \
npm install express && \
npm install --save-dev typescript @types/node @types/express ts-node-dev
  • 使用下面的代码创建文件
    tsconfig.json
{
    "compilerOptions": {
      "allowJs": true,
      "target": "ES6",
      "module": "commonjs",
      "strict": true,
      "esModuleInterop": true,
      "skipLibCheck": true,
      "outDir": "./dist",
      "rootDir": "./src"
    },
    "include": ["src"]
  }  
  • 使用以下代码创建文件`src/greeting.js
export function greeting() {
    return "Hello from JS"
}
  • 使用下面的代码创建文件
    src/index.ts
import express, { Request, Response } from 'express';
import { greeting } from './greeting.js';

const app = express();
const port = 3000;

app.get('/', (req: Request, res: Response) => {
  res.send(greeting());
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

如何将ad dart函数编译为js

然后导入它并在index.ts中使用它

dart 代码示例:

String greeting() => 'Hello from Dart';

笔记

赏金

我非常感谢实际的可运行代码或基于特意最小的代码示例实现它的详细步骤

dart dart2js
2个回答
0
投票
首先设置你的 dart2js

$ pub global activate dart2js_info
没有打开cmd并在dart中创建新项目

dart create dart_to_js
进入目录

cd dart_to_js
使用此命令或在任何 IDE 中打开您的项目

code .
现在在 VS Code 或 IDE 中打开您的项目。你会看到一个 

lib 文件夹,你会得到一个 main.dart 文件。

在 main.dart 中,您需要编写要在 js 中使用的函数 例如

// lib/main.dart String greeting() { return 'Hello from Dart'; } void main() { print(greeting()); } @JS() library main; import 'package:js/js.dart'; @JS('greeting') external String greeting();
根据需要导入库或添加注释。

dart compile js lib/main.dart -o build/main.dart.js
运行此命令,您将在 

build 文件夹中获得编译后的版本。 现在我们将这个 dart 代码集成到 Js 中。

cd node_project npm init -y npm install express npm install --save-dev typescript @types/node @types/express ts-node-dev
你的 tsconfig.json 看起来像这样

{ "compilerOptions": { "allowJs": true, "target": "ES6", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src"] }
现在在 src 文件夹中创建greetings.js 或index.ts 文件。

//you can also provide path from your pc to import after adding path in to packages file. or simply create a dart project inside your node project. const dartGreeting = require('../../dart_to_js/build/main.dart.js');
根据需要设置您的服务器。

import express, { Request, Response } from 'express'; import { greeting } from './greeting.js'; const app = express(); const port = 3000; app.get('/', (req: Request, res: Response) => { res.send(greeting()); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); npx ts-node-dev src/index.ts
运行项目,一切顺利


0
投票
我不确定仅使用

dart compile js

 和可用选项是否可以做到这一点。

您可以编写一个脚本来从 dart 构建中提取要转换为 JavaScript 模块的函数,但前提是您将其包装在

main()

 中并调用它。使用 Dart 生态系统中的另一种工具可能有一种更简单的方法,但快速搜索并没有找到。

给出

greeting.dart

String greeting() => "Hello from Dart"; void main() { greeting(); }
编译它

不进行优化

dart compile js -O0 -o greeting-dart.js greeting.dart
现在,您必须编写脚本。它看起来像这样:

import { readFile, writeFile } from "node:fs/promises"; import { parse } from "acorn"; import { simple } from "acorn-walk"; import MagicString from "magic-string"; const convertToJsModule = async () => { const contents = await readFile("./greeting.js"); const ast = parse(contents.toString(), { ecmaVersion: 2023 }); const magic = new MagicString(contents.toString()); const found: string[] = []; simple(ast, { ObjectExpression(node) { node.properties.forEach((property) => { if (property.type === "Property") { if ( property.key.type === "Identifier" && property.key.name === "greeting" ) { found.push(magic.snip(property.start, property.end).toString()); } } }); }, }); if (found.length) { await writeFile("greet.js", `export function ${found[0]}`); } }; convertToJsModule();
这是有效的,因为未经优化的 

dart compile js

 会将您的函数创建为对象的 
FunctionExpression
 属性。像这样的东西:

var A = { greeting() { return "Hello from Dart"; }, main() { A.greeting(); }, }
现在

greet.js是一个包含以下内容的文件:

export function greeting() { return "Hello from Dart"; }
您可以像往常一样将其导入到

src/index.ts

import express, { Request, Response } from 'express'; import { greeting } from './greet.js'; const app = express(); const port = 3000; app.get('/', (req: Request, res: Response) => { res.send(greeting()); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
将这些步骤添加到 

scripts

 内的 
package.json
 中会很容易。尝试这个很有趣,所以我创建了一个 CLI 工具来为您完成此操作
dartscript

您可以执行

npm i dartscript --save-dev

,然后将其添加到您的package.json

"scripts": { "build:dart": "dart compile js -O0 greeting.dart", "build:dart:js": "dartscript -o greeting.js greeting" }
然后运行 

npm run build:dart

npm run build:dart:js

© www.soinside.com 2019 - 2024. All rights reserved.