alphagov / accessible-autocomplete

An autocomplete component, built to be accessible.
https://alphagov.github.io/accessible-autocomplete/examples/
MIT License
915 stars 149 forks source link

Can't make it work using rollup.js #552

Open astagi opened 2 years ago

astagi commented 2 years ago

Hello,

I'm trying to use your component using rollup.js

import accessibleAutocomplete from 'accessible-autocomplete'

I get this error

 [!] Error: 'default' is not exported by node_modules/accessible-autocomplete/dist/accessible-autocomplete.min.js, imported by src/js/plugins/select-autocomplete.js
colmjude commented 2 years ago

How are you trying to use it? Are you trying to include it in your bundle or are you trying to access it in your code as per the example?

If the latter, then once you install with

npm install --save accessible-autocomplete

You should be able to create a js file that 'imports' and uses it. E.g. test.js

import accessibleAutocomplete from 'accessible-autocomplete'

const countries = [
  'France',
  'Germany',
  'United Kingdom'
]

accessibleAutocomplete({
  element: document.querySelector('#my-autocomplete-container'),
  id: 'my-autocomplete', // To match it to the existing <label>.
  source: countries
})

'Import' here tells rollup that this (accessible-autocomplete) external dependency should be available when the js is run.

Add the js file to compile to rollup.config.js, e.g.

module.exports = [
  {
    input: 'src/javascripts/test.js',
    output: {
      file: 'application/static/javascripts/test.js',
      format: 'iife'
    }
  }
]

Then, when you run rollup it should output something like

(function (accessibleAutocomplete) {
  'use strict';

  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

  var accessibleAutocomplete__default = /*#__PURE__*/_interopDefaultLegacy(accessibleAutocomplete);

  const countries = [
    'France',
    'Germany',
    'United Kingdom'
  ];

  accessibleAutocomplete__default["default"]({
    element: document.querySelector('#my-autocomplete-container'),
    id: 'my-autocomplete', // To match it to the existing <label>.
    source: countries
  });

})(accessibleAutocomplete);

Expecting accessibleAutocomplete to be available globally.

Which it should be if the script has been added to the HTML file before this script. E.g.

<script src="{{ assetPath }}/accessible-autocomplete.min.js"></script>
<script src="{{ assetPath }}/test.js"></script>

If you want to include the accessible-autocomplete code in your bundle/script then I think you need to use the @rollup/plugin-node-resolve plugin.

Hope that helps.