railsware / js-routes

Brings Rails named routes to javascript

Home Page:http://railsware.github.io/js-routes/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Want to export as named (not default), but failing in AMD setup

nerdcave opened this issue · comments

I'd like to export the routes as a named object so I can export others consts in the same file:

// constants.js.erb
const routes = {};
(function() {
  <%= JsRoutes.generate(namespace: "all") %>
}.call(routes))

export const JS_ROUTES = routes.all

export const WHATEVER = '<%= Rails.application.secrets.whatever %>'
// consumer.js
import * as ALL from 'constants'
import {JS_ROUTES} from 'constants'

console.log('ALL keys', Object.keys(ALL))
console.log('JS_ROUTES keys', Object.keys(JS_ROUTES || {}))

This works in my web app (webpacker/babel/rails-erb-loader/etc) and it outputs what's expected:

ALL keys, ['JS_ROUTES', 'WHATEVER']
JS_ROUTES keys, ['user_path', ...]

However, this fails in my karma/jasmine test setup and it outputs:

ALL keys, ['user_path', ...]
JS_ROUTES keys, []

The JsRoutes.generate(namespace: "all") call is basically clobbering all the file's exports (even if I remove the line export const JS_ROUTES = routes.all). The AMD check here https://github.com/railsware/js-routes/blob/master/lib/routes.js#L516 seems to partially be the cause because my test setup apparently uses RequireJS.

Any thoughts?

@le0pard why do we check for define.amd to present not just define?

@nerdcave does RequireJS define define.amd?

The AMD check seems pretty standard, so I guess my question comes down to the result it causes. In other words, is it expected that the JsRoutes.generate() call clobbers the file exports in this way? My guess is no, but I'm not familiar enough with RequireJS environments and/or AMD checking to really know.

I think the bug is in the namespace. Overall I think namespace is something you should avoid because it is designed for retro JS projects.

You should be using:

const routes = <%= JsRoutes.generate(namespace: "") %>
export const JS_ROUTES = routes

I actually required a change to always return the routes object from the wrapper function. Please check v 1.4.9

Assuming this is solved in v1.4.9. Feel free to follow up.