Issue
I’m using dart2js
to compile dart to JavaScript on my Ubuntu server.
I’m able to use simple commands like print()
but I can’t seem to use the DOM.
The code below is returning null
.
Is there something else I need to make imports work besides including the compiled out.js
?
import 'dart:html';
void main() {
print(document.querySelector('body'));
}
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="/css/f4cacce_main_1.css" />
<script src="/js/51de0d2_main_1.js"></script>
</head>
<body>
</body>
</html>
Solution
If you import out.js
manually then the issue is probably in your HTML file. Please add it to your question.
You should use pub build
instead of dart2js
(pub build
uses dart2js
internally). pub build
takes care of adding the script tag for the generated JavaScript.
Edit
Your HTML should look like this before you run pub build
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="/css/f4cacce_main_1.css" />
</head>
<body>
<script type="application/dart" src="main1.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
(assuming main1.dart
is the file containing your Dart code).
You can open this in Dartium without building to JavaScript.
You can also serve this using pub serve
and then open it from Dartium or non-Dart capable browsers and pub serve
always returns the correct output (Dart or JS)
Answered By – Günter Zöchbauer
Answer Checked By – Terry (FlutterFixes Volunteer)