Skip to content

Commit f41e0be

Browse files
committed
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. The spec is a little odd, as I wanted to avoid rewriting the comment in the routes file to avoid saying module.exports, so it strips out single-line javascript comments.
1 parent d104a8f commit f41e0be

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-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: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
require 'spec_helper'
2+
require 'byebug'
23

34
describe JsRoutes, "options" do
45

@@ -522,6 +523,15 @@
522523
end
523524
end
524525

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

0 commit comments

Comments
 (0)