diff --git a/CHANGELOG.md b/CHANGELOG.md index 36741302..6aae7fce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,11 @@ * Add a top-level `warn()` function for custom functions and importers to print warning messages. +### JavaScript API + +* Avoid re-assigning the `require()` function to make the code statically + analyzable by Webpack. + ## 1.20.3 * No user-visible changes. diff --git a/lib/src/io/node.dart b/lib/src/io/node.dart index 4f003dfb..6959b950 100644 --- a/lib/src/io/node.dart +++ b/lib/src/io/node.dart @@ -87,10 +87,8 @@ class Stderr { void flush() {} } -@JS("require") -external _FS _require(String name); - -final _fs = _require("fs"); +@JS("fs") +external _FS get _fs; @JS("process") external _Process get _process; diff --git a/lib/src/node/chokidar.dart b/lib/src/node/chokidar.dart index 747e7f8f..8ceb972e 100644 --- a/lib/src/node/chokidar.dart +++ b/lib/src/node/chokidar.dart @@ -4,9 +4,6 @@ import 'package:js/js.dart'; -@JS("require") -external Chokidar _require(String name); - @JS() class Chokidar { external ChokidarWatcher watch(String path, ChokidarOptions options); @@ -30,4 +27,5 @@ class ChokidarWatcher { /// The Chokidar module. /// /// See [the docs on npm](https://www.npmjs.com/package/chokidar). -final chokidar = _require("chokidar"); +@JS("chokidar") +external Chokidar get chokidar; diff --git a/tool/grind/npm.dart b/tool/grind/npm.dart index e964e520..1b77d9cc 100644 --- a/tool/grind/npm.dart +++ b/tool/grind/npm.dart @@ -42,7 +42,13 @@ void _js({@required bool release}) { // * We thoroughly test edge cases in user input. if (release) ...["-O4", "--fast-startup"] ]); - var text = destination.readAsStringSync(); + var text = destination + .readAsStringSync() + // Some dependencies dynamically invoke `require()`, which makes Webpack + // complain. We replace those with direct references to the modules, which + // we load explicitly after the preamble. + .replaceAllMapped(RegExp(r'self\.require\("([a-zA-Z0-9_-]+)"\)'), + (match) => "self.${match[1]}"); if (release) { // We don't ship the source map, so remove the source map comment. @@ -50,7 +56,16 @@ void _js({@required bool release}) { text.replaceFirst(RegExp(r"\n*//# sourceMappingURL=[^\n]+\n*$"), "\n"); } - destination.writeAsStringSync(preamble.getPreamble() + text); + // Reassigning require() makes Webpack complain. + var preambleText = + preamble.getPreamble().replaceFirst("self.require = require;\n", ""); + + destination.writeAsStringSync(""" +$preambleText +self.fs = require("fs"); +self.chokidar = require("chokidar"); +self.readline = require("readline"); +$text"""); } @Task('Build a pure-JS dev-mode npm package.')