Mike
Mike

Reputation: 5826

ES6 function not available

I'm getting the following error:

namesearch.js:5 Uncaught ReferenceError: autoComplete is not defined at Namesearch (namesearch.js:5)

./index.js

import autoComplete from '@tarekraafat/autocomplete.js/dist/js/autoComplete';
import Namesearch from './components/namesearch';

document.addEventListener('DOMContentLoaded', function () {
    console.log(' DOM is now safely manipulable.');
    Namesearch();
});

./components/namesearch.js

export default function () {

    console.log("autoComplete function");

    const autoCompletejs = new autoComplete({
        data: {                        
            src: async () => {
            ...

If I put the logic directly into index.js everything works, but I would like to do things more modular. What have I missed here?

Upvotes: 1

Views: 246

Answers (3)

laktherock
laktherock

Reputation: 429

Each file is a module, that has its own scope of variables. When you import module into the file. You are adding this to the module scope, but not to the global scope.

Hence It is not available on the other file. So we have to import on every file wherever it is required.

There is no other way you need to import this

import autoComplete from '@tarekraafat/autocomplete.js/dist/js/autoComplete';

Upvotes: 0

yqlim
yqlim

Reputation: 7108

You need to import autoComplete inside Namesearch.js, not in the index.js.

Scopes using ES6 modules are different compared to using <script>.

Everything that is imported/defined in one scope is not going to be available in any children scopes, and not availble to parent scope unless being exported.

Upvotes: 1

Thales
Thales

Reputation: 346

You need to import autoComplete at namesearch.js.

import autoComplete from '@tarekraafat/autocomplete.js/dist/js/autoComplete';

export default function () {

    console.log("autoComplete function");

    const autoCompletejs = new autoComplete({
        data: {                        
            src: async () => {
            ...

Upvotes: 3

Related Questions