我一直在努力控制导入和导出,这样我就可以精简我的 JS 应用程序。我试过合并这些 Mozilla和 this Stack Overflow examples没有任何运气。 It looks like Chrome should support this now .我不确定我做错了什么。
我在 export.js 中有一个这样的函数:
export crossingover() {
dynamicText.setText('Some text');
canvas.renderAll();
}
我像这样在我的主 app.js 文件中导入上面的内容,原始函数是:
import { crossingover } from 'export';
在我的 index.html 文件中有两个脚本标签:
<script src="app.js"></script>
<script type="module" src="export.js"></script>
在我看来,结果应该与现在在 app.js 中导入的原始函数相同,但它会破坏应用程序。我错过了什么?
我在检查我的应用程序时遇到了这 2 个错误:
Uncaught SyntaxError: Unexpected token {
index.html:1 Access to Script at 'file:///myappdirectory/export.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
最佳答案
首先,您的导入路径需要类似路径:
import { crossingover } from './export.js';
然后你只需要有一个 app.js
的脚本标签,这应该是 module
类型:
<script type="module" src="app.js"></script>
最后,导出的语法需要是:
export function crossingover() {
[...]
更新
我没有意识到的另一件事 - 在您更新的答案中,您透露您正在从 file:///
URL 提供服务。您浏览器中的安全设置可能不允许从文件 URL 加载 JS 模块 - 相反 run a local web server并将其加载到您的网络浏览器中。
关于javascript - 坚持 import/export ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48063437/