Recently, I was working on a project that was using vanilla JS. I needed to relocate some of the code I wrote from a raw script tag to a .js
file. The code fully worked before I moved it. While I was moving the JS code, I was also relocating PHP and HTML elements. However, midway through this move, disaster struck, and I was left troubleshooting why things stopped working. With a bit of luck, I determined that this was caused by the import
statement I used in the new JS file. That’s where things got a little weird.
Working import example
<script type="module">
import { myCustomFunction } from 'some/file/path.js';
</script>
Failed import example
import { myCustomFunction } from 'some/file/path';
The reason why this one was a bit strange wasn’t the fact that import didn’t work but rather the characteristics caused by the imports not working.
- No errors were thrown in the console
- No missing files were detected
- Other functions within the file were not being executed
- Console logs after the import didn’t work either
- The project-specific context of the code’s location made troubleshooting a little bit more difficult
- New PHP errors were being thrown as a result of the JS not working
With all of these characteristics in mind, I went through the normal checks of whether I wrote the import and exports properly, and with no luck. In this case, the error was caused by the way the JS file was enqueued. Next, I wanted to understand more deeply: why did it work before, and why doesn’t it work now? Make it make sense.
Here’s what I realized after a bit of documentation reading. A common pattern for loading JS into a PHP/HTML involves using a script tag with src
or just inlined JS. Most of the time, we don’t declare type="module"
. If I had to guess, it’s because it’s not a well-known attribute, it’s newer and has less browser support, and in most cases, you might not even need it. On projects where your code is compiled, there’s a good chance your imports are being handled automatically by the compiler.
See a live code example on code sandbox
<script src="./script.js"></script>
<script type="module" src="./script.js"></script>
As a result, it caused me to reflect on this topic and take a moment to understand why I didn’t catch this faster. Here are a few reasons I think this could easily trip up people, especially if you’re in an area where you didn’t write the code or load the JS file.
- Working mostly on projects that are compiled, imports get handled during the compilation step and this might not be your first train of thought during troubleshooting.
- The lack of error logging made it hard to determine the root issue. If you don’t catch it immediately, you might go too far before you realize it’s broken.