-1

Using AlpineJS I have the folowing HTML and JS:

<form x-data="inquiry()" x-on:submit.prevent="submit" method="post">
</form>

<script>
  function inquiry() {

    return {

      data: { name: "" },

      submit() {
        // Do something
      }
    }
  }
</script>

I moved the JS inquiry function to a JS file and used Parcel for building.

So the index.js file used as an entry point for Parcel is:

import './index.less'  

import inquiry from './inquiry.js' 

import alpine from 'alpinejs';

window.alpine = alpine;
alpine.start();

console.log("Hello");

I am importing the bundle in my HTML page using:

<script src="~/index.js" type="text/javascript" defer></script>

When I run my code and try to access inquiry function I get the error:

Alpine Expression Error: Can't find variable: inquiry

However I can see "Hello" in the console as result of console.log("Hello")

What am I missing?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • How are you loading your scripts, could you perhaps show med the script-tags? – Fralle Oct 23 '22 at 14:46
  • Maybe you forget to import this bundle in html. – bbbbbbbboat Oct 23 '22 at 14:47
  • 1
    @Fralle I am using ` ` – Miguel Moura Oct 23 '22 at 14:51
  • @bbbbbbbboat No I am not. I just added `console.log("Hello")` in my index.js file and it shows in the console when I run the application. – Miguel Moura Oct 23 '22 at 14:52
  • Fine. How about the source code where the error is throwed? It looks like it is calling a `global variable` which is declared by `var` or registered in `window`. But now you are importing it into the capsule of `index.js` module. I'm not familar with `alphine`, I hope I can help you a little. – bbbbbbbboat Oct 23 '22 at 15:00
  • @bbbbbbbboat The error is throned when I submit the form. It can't find inquiry() function and the submit method. – Miguel Moura Oct 23 '22 at 15:31

1 Answers1

0

You might need to use modules. Could you set this attribute on the script tag?

<script src="~/index.js" type="module" defer></script>

Also ensure that you are correctly exporting inquiry from that file.

Fralle
  • 889
  • 6
  • 12