Blog logotrial and stderr

javascript

A 2 post collection


Javascript Module Systems in 30 Seconds

 •  Filed under javascript

Here's my attempt at the most compact description of Javascript module systems on the internet:

ES6 (aka ES Harmony)

import a from 'b'
export c

CommonJS

var a = require(‘b’)
exports = c

CommonJS is synchronous, and supports one file per module.

NodeJS is a CommonJS variant

var a = require(‘b’)
modules.exports = c

AMD

define(['a', 'b'], function(a, b) { return c })

AMD supports multiple files per module.

RequireJS is a loader that implements AMD and loads plain JS files as modules

Enums in React

 •  Filed under react, javascript

I wrote a component that held an Enum, made in the popularly-recommended fashion, as state:

const MyEnum = Object.freeze({
    FOO: Symbol('foo'),
    BAR: Symbol('bar'),
})

class MyThing extends Component {
  constructor(props) {
    super(props)
    this.state = { enumValue = MyEnum.FOO }
  }
  
  render() {
    return({
      this.state.enumValue === MyEnum.FOO ?
        <p>I pity the foo</p> :
        this.state.enumValue === MyEnum.BAR ?
          <p>I pity the bar</p> :
          <p>I pity myself</p>
    })
  }
}

and suddenly my app was breaking on hot-reloads, and I had written pitiably broken code! It seemed like the state was somehow becoming invalid whenever a hot reload happened.

This is because the hot reloader preserves the state, but every time the component is reloaded, our ES6 engine generates a new unique value for each Symbol, so the comparison this.state.enumValue === MyEnum.FOO is comparing an old value of MyEnum.FOO to the current one, yeilding false. So use an enum with deterministic values, like, say,

const MyEnum = Object.freeze({
    FOO: Symbol.for('foo'),
    BAR: Symbol.for('bar'),
})