Shopify / sprockets-commoner

Use Babel in Sprockets to compile JavaScript modules for the browser
MIT License
182 stars 22 forks source link

Requires not cached? #58

Closed benogle closed 7 years ago

benogle commented 7 years ago

It seems every time a module is required, it is evaluated anew. e.g. using local variables to deal with singletons or maintain a 'global' id dont work.

// In some-module.js
let number = 0
module.exports = {
  increment: function () {
    return number++
  }
}
// In another-module.js
const SomeModule = require('some-module')
console.log(SomeModule.increment())
// In a-third-module.js
const SomeModule = require('some-module')
console.log(SomeModule.increment())
// In application.js

// Prints 0 twice
require('another-module')
require('a-third-module')

This is a problem requiring jquery plugins that require jquery.

// In some-plugin.js
const jQuery = require('jquery')
jQuery.fn.somePlugin = function () {
  console.log('do stuff')
}
// In application.js
const $ = require('jquery')
require('some-plugin')

// somePlugin deosnt exist cause our jquery and somePlugin's are different
$('.aselector').somePlugin()

Is this by design? Will it be fixed to match the node, webpack et al behavior?

benogle commented 7 years ago

This was an issue across sprockets requires. I've replaced all sprockets requires with require() and things function as expected.