纯JavaScript中如何在另一个文件中引入类文件?
Fixing ES Module Import for Your Pure JavaScript Class
The issue here is that you're using ES Module syntax (export/import) but haven't configured your scripts to be treated as modules by the browser. Here's how to fix it step by step:
Step 1: Update Your HTML Script Tags
Mark your scripts as ES Modules by adding type="module" to the script tag. You only need to include the entry script (global.js) since it will import editable.js automatically:
<!DOCTYPE HTML> <html lang="fr"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="Content-Type" content="UTF-8"> <!-- Mark the script as a module --> <script type="module" src='global.js'></script> </head> <body> </body> </html>
Step 2: Import the Editable Class in global.js
Add an import statement at the top of global.js to bring in the Editable class from editable.js. Remember to use a relative path (with ./) for local files:
// Import the Editable class from the adjacent file import { Editable } from './editable.js'; window.addEventListener('load', Init); function Init() { var test = new Editable(); // This will now run and show the alert! }
Step 3: Keep Your Editable Class as an Export
Your editable.js is already correct with the export keyword—no changes needed here:
export class Editable { constructor() { alert("hello"); } }
Why This Works
- ES Modules Require
type="module": Without this attribute, the browser ignoresexport/importsyntax, so yourEditableclass never becomes accessible outside its file. - Module Scope: ES Modules have their own private scope, so variables/classes aren't added to the global window object by default. Using
importis the proper way to access code from another module. - Automatic Dependency Loading: When you import
editable.jsinglobal.js, the browser will automatically fetch and loadeditable.jsbefore executingglobal.js, so you don't need to include it separately in your HTML.
内容的提问来源于stack exchange,提问作者Entretoize
相关产品推荐
相关产品推荐

