Skip to content

Commit 94aef98

Browse files
bagedevimobogdan
andauthored
Obfuscate assignment to module.exports to prevent warnings (#338)
Obfuscate assignment to module.exports to prevent warnings Some javascript bundles (like vite) emit warnings when they encounter module.export in an ESM module. This just hides that assignment a little so that that warning doesn't appear. --------- Co-authored-by: Bogdan Gusiev <[email protected]>
1 parent d104a8f commit 94aef98

File tree

4 files changed

+25
-2
lines changed

4 files changed

+25
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## Pending
4+
5+
* Obfuscate assignment to module.exports in order to prevent warnings in javascript bundlers, like Vite. Fixes [#337](https://github.com/railsware/js-routes/issues/337).
6+
37
## [2.3.6]
48

59
* Fixed serialization of empty `Array` and empty `Hash`. Fixes [#336](https://github.com/railsware/js-routes/issues/336).

lib/routes.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ RubyVariables.WRAPPER(
2727
CJS: {
2828
define(routes) {
2929
if (module) {
30-
module.exports = routes;
30+
// Some javascript processors (like vite/rolldown)
31+
// warn on using `module.exports` in an ESM module.
32+
// This just obfuscates that assignment a little so
33+
// users don't get a warning they can't fix.
34+
const _mod = module;
35+
_mod.exports = routes;
3136
}
3237
},
3338
isSupported() {

lib/routes.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,12 @@ RubyVariables.WRAPPER(
147147
CJS: {
148148
define(routes) {
149149
if (module) {
150-
module.exports = routes;
150+
// Some javascript processors (like vite/rolldown)
151+
// warn on using `module.exports` in an ESM module.
152+
// This just obfuscates that assignment a little so
153+
// users don't get a warning they can't fix.
154+
const _mod = module;
155+
_mod.exports = routes;
151156
}
152157
},
153158
isSupported() {

spec/js_routes/options_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,15 @@
522522
end
523523
end
524524

525+
describe "module.exports usage" do
526+
it "doesn't include module.exports" do
527+
# We mention `module.exports` in the comments of routes.ts, just so it's clear
528+
# why the expression is so weird there.
529+
js_without_comments = generated_js.lines.map { it.gsub(/\/\/.*$/, "") }.join("\n")
530+
expect(js_without_comments).not_to include("module.exports")
531+
end
532+
end
533+
525534
describe "banner option" do
526535
let(:_options) { {banner: nil} }
527536

0 commit comments

Comments
 (0)