You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯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 ignores export/import syntax, so your Editable class 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 import is the proper way to access code from another module.
  • Automatic Dependency Loading: When you import editable.js in global.js, the browser will automatically fetch and load editable.js before executing global.js, so you don't need to include it separately in your HTML.

内容的提问来源于stack exchange,提问作者Entretoize

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:40:54