Choices: dist/choices.min.js does not export a variable

Created on 17 Oct 2016  路  4Comments  路  Source: Choices-js/Choices

The main dist file doesn't export a useful value. It simply gives you {}.

import Choices from 'choices.js'
new Choices()  // Error: Choices is not a function
console.log(Choices)  // => Object {}

Same effect with require().

var Choices = require('choices.js')
new Choices()  // Error: Choices is not a function
console.log(Choices)  // => Object {}

What it actually does is export window.Choices. This works, contrary to commonjs expectations:

require('choices.js')
new window.Choices(element)

cc @akosipc who first encountered this bug.

Most helpful comment

In version 2.2.4 Webpack now wraps Choices in a UMD wrapper. This means you should be able to import it using require('choices.js') or import Choices from 'choices.js'. If it is included directly on the page, it will be attached to the global window.

If there are any issues with the new version, let me know ASAP!

Thanks 馃憤

All 4 comments

I don't know exactly why this is, but here's something strange.

In choices.js line 2175, it sets window.Choices and module.exports.

2175  window.Choices = module.exports = Choices;

This is in conflict with export default in line 34.

34    export default class Choices {

I recommend:

  • don't use export default, instead just use module.exports. This allows you to make a package that can be used by both ES5 (require(...)) and ES6 transpilers (import).
  • Alternatively, just use export default instead; however, be aware of the caveat of this. redux-thunk is one package that follows this convention.
  • Avoid setting window.Choices explicitly. This will avoid global namespace pollution. Instead, generate a UMD build with Webpack. (I think that's libraryTarget: 'umd', but i'm not much of a Webpack user...)

I think module is just getting shadowed.

This is how I solved the problem ...

At the top of choices.js:
const CJSModule = module;

Then replace exports.default and window.Choices with:
CJSModule.exports = Choices;

Then you can:
import Choices from 'choices.js'

:)

In version 2.2.4 Webpack now wraps Choices in a UMD wrapper. This means you should be able to import it using require('choices.js') or import Choices from 'choices.js'. If it is included directly on the page, it will be attached to the global window.

If there are any issues with the new version, let me know ASAP!

Thanks 馃憤

This worked for me using Typescript
import * as Choices from 'choices.js'

Was this page helpful?
0 / 5 - 0 ratings