Search code examples
javascriptastrojs

Unable to resolve JavaScript File when Building with Astro


I am exploring potentially building a site using the Astro framework. As such I am working through the tutorial. Unfortunately something is not quite working right and its baffling me as to what the cause may be. I'm at the point where it tells you to insert JavaScript into a script tag in one of the components. My understanding of the documentation is the process is supposed to more or less "just work". One creates a script tag and imports the JS file, then Astro builds it. Instead I see the following errors when building the website:

5:52:14 PM: 22:52:14 [ERROR] [vite] x Build failed in 15ms
5:52:14 PM: Could not resolve "../scripts/menu.js" from "src/pages/blog.astro?astro&type=script&index=0&lang.ts"
5:52:14 PM: file: /opt/build/repo/src/pages/blog.astro?astro&type=script&index=0&lang.ts
5:52:14 PM:   Stack trace:
5:52:14 PM:     at getRollupError (file:///opt/build/repo/node_modules/rollup/dist/es/shared/parseAst.js:396:41)
5:52:14 PM:     at ModuleLoader.handleInvalidResolvedId (file:///opt/build/repo/node_modules/rollup/dist/es/shared/node-entry.js:20216:24)
5:52:14 PM: ​
5:52:14 PM: "build.command" failed                                        
5:52:14 PM: ────────────────────────────────────────────────────────────────

The above comes from Netlify, but also occurs when I run the build command on my dev server. Here is the Astro/HTML code:

  <body>
    <Header />
  
    <h1>{pageTitle}</h1>
    <p>This is where I will post about my journey learning Astro.</p>
    
    <ul>
      <li><a href="/posts/post-1/">Post 1</a></li>
      <li><a href="/posts/post-2/">Post 2</a></li>
      <li><a href="/posts/post-3/">Post 3</a></li>
    </ul>
    
    <Footer />
  <script>
    import '../scripts/menu.js';
  </script>
  </body>

And here are the contents of menu.js:

document.querySelector('.hamburger').addEventListener('click', () => {
    document.querySelector('.nav-links').classList.toggle('expanded');
  });

When I searched Google for answers it led me to add a MIME type to the script tag which prompts Astro to not process the JavaScript. This technically allows the build to complete, but does not help as the JavaScript won't appear in the final web page. Can anyone point me in the direction of what is going wrong?


Solution

  • The issue turned out to be the file path. I made a post on Reddit about this issue and one user pointed out

    <script>
      import '../scripts/menu.js';
    </script>
    

    Really should be

    <script>
      import '../assets/scripts/menu.js';
    </script> 
    

    Once I made the change the page built as expected.