我想将 dart 编译为 js 以用于非 Web 目标(例如 fermyon/js 或
node
)
更新:
我被告知这是可能的,虽然我找不到任何具体的文档
似乎有两种可能的方法:
这里是使用
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"]
}
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}`);
});
然后导入它并在index.ts中使用它
dart 代码示例:
String greeting() => 'Hello from Dart';
$ 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
运行项目,一切顺利
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
。