How to fix 'Uncaught ReferenceError: XXX is not defined' when importing a class

How to fix 'Uncaught ReferenceError: XXX is not defined' when importing a class

我遇到了麻烦 importing/exporting 类。看起来很随意。有时它会起作用,有时它不会。

我收到以下控制台错误: 未捕获的 ReferenceError:未在 main.js:

处定义测试

我已经在线上传了这个测试http://tibbotts.epizy.com/testClassImport/index.html

我试过将“./test.js”更改为“/test.js”、“./test”等。

我尝试在网上搜索解决方案,但所有解决方案都针对脚本类型="module" ...修复。

<!DOCTYPE html>

<html>

<head>
    <title>Test Class Importing</title>
    <script type="module" src="main.js"></script>
</head>

<body>
    hello this is a test
</body>

</html>
import Test from "./test.js";

test = new Test();

test.speak();
export default class Test{

    constructor(test){
        this._test = `Test is Successful`;
    }

    speak(){
        console.log(this._test);
    }

}

我希望它能够控制台日志 Test is Successful 并导入脚本,但我却收到以下错误消息:Uncaught ReferenceError: test is not defined at main.js:

您可能希望使用关键字 varlet 来初始化 test :

let test = new Test();

另外不要忘记您的构造函数需要一个参数:

let test = new Test("something");