JavaScript ES模块import/export报错及模块加载失败求助
Hey there! Let's work through those module-related errors you're hitting with your Flask + Firefox setup. I'll break down the root causes and walk you through step-by-step fixes.
First, Let's Understand the Errors
- Initial
SyntaxErrorfor import/export: Browsers treat regular<script>tags as "classic scripts" by default, which don't support ES module syntax (import/export). You need to explicitly tell the browser these are modules. - Loading failed after switching to
.mjs: Flask doesn't recognize.mjsfiles out of the box—it sends them with atext/plainMIME type, which browsers reject for modules. Plus, you had a small syntax typo in yourAddButton.jsthat was breaking script execution.
Step 1: Update Your HTML Script Tags
Modify your <script> tags to declare them as modules. You can either keep using .js extensions (simpler) or stick with .mjs—just make sure the src path matches and you set type="module":
<html> <head> <meta charset="UTF-8"> <!-- Switch to UTF-8 to avoid character encoding issues --> <script type="module" src="/static/js/AddButton.js"></script> <!-- If you use .mjs, change src to /static/js/AddButton.mjs --> <title>{{title}}</title> </head> <body> <button type="button" onclick="AddForm()"> + </button> <div id="newFormHere"></div> <form action="javascript: SendFetchRequest()" id="Form2"> Ticker2: <input type="text" id="Ticker2" value="GOOG"> <input type="submit" value="Submit"> <div id="FetchRequestOutput"></div> </form> </body> </html>
Step 2: Fix Flask's MIME Type Handling (If Using .mjs)
If you want to keep using .mjs extensions, add this to your Flask app file (e.g., app.py) to ensure Flask sends .mjs files with the correct text/javascript MIME type:
from flask import Flask import mimetypes app = Flask(__name__) # Add MIME type mapping for .mjs files mimetypes.add_type('text/javascript', '.mjs') # ... rest of your Flask routes and logic ...
If you stick with .js extensions, you can skip this step—Flask already handles .js files correctly.
Step 3: Fix Your JavaScript Code
SendRequest.js (or SendRequest.mjs)
Clean up the export syntax and add basic error handling for the fetch call:
// Define and export the function in one cleaner step export function SendFetchRequest() { const tickerInput = document.getElementById("Ticker2"); fetch(`action_page?Ticker=${tickerInput.value}`) .then(response => response.text()) .then(data => { document.getElementById("FetchRequestOutput").innerHTML = data; }) .catch(error => console.error('Fetch error:', error)); // Add error logging to debug issues }
AddButton.js (or AddButton.mjs)
Fix the typo (mysubmit,setAttribute → mysubmit.setAttribute) and expose the AddForm function globally (modules keep variables private by default, so your HTML's onclick won't find it otherwise):
// Use a relative path if both files are in the same /static/js folder import { SendFetchRequest } from './SendRequest.js'; function AddForm() { const myform = document.createElement("FORM"); myform.setAttribute("id", Math.random()); myform.action = "javascript: SendFetchRequest()"; const myinput = document.createElement("INPUT"); myinput.setAttribute("type", "text"); myinput.setAttribute("value", "SomeDefaultValue"); myinput.setAttribute("name", "Ticker"); // Add name attribute for backend compatibility const mysubmit = document.createElement("INPUT"); mysubmit.setAttribute("type", "submit"); // Fixed the comma typo here! mysubmit.setAttribute("value", "Submit"); myform.appendChild(myinput); myform.appendChild(mysubmit); document.getElementById("newFormHere").appendChild(myform); } // Expose AddForm to the global window object so onclick can access it window.AddForm = AddForm;
Key Notes to Remember
- Module Scope: ES modules don't automatically expose variables/functions to the global scope. That's why we need
window.AddForm = AddForm—so your HTML'sonclickhandler can call the function. - Relative Paths: Using
./SendRequest.jsinstead of an absolute path is more reliable if your script files live in the same directory. - Error Handling: Adding
.catch()to yourfetchcall will help you debug any issues with the request itself, like network failures or backend errors.
After making these changes, restart your Flask server, clear Firefox's cache, and test again—it should work without those module errors!
内容的提问来源于stack exchange,提问作者Vittorio Apicella

