导入在Chrome中不起作用 [英] import not working in Chrome

查看:169
本文介绍了导入在Chrome中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用原始JavaScript创建一个单页应用程序.我想将代码组织在不同的文件中以使其模块化,这意味着我应该能够访问另一个文件中一个文件中定义的功能.我为此使用ES6本机import export:

I am creating an single page app in vanilla JavaScript. I want to organize my code in different files to make it modular, which means I should be able to access functions defined in one file in another file. I am using ES6 native import export for this:

file-1.js:

file-1.js:

export function func1() {}
export function func2() {}

file-2.js:

file-2.js:

import { func1, func2 } from './file-1';

index.html:

index.html:

<script src="file-1.js"></script>

当我在Chrome(版本65)中运行index.html时,出现以下错误: Uncaught SyntaxError: Unexpected token {.

When I run index.html in Chrome (version 65), I get the following error: Uncaught SyntaxError: Unexpected token {.

我的代码有什么问题? Chrome 65完全支持ES6模块系统.

What's wrong in my code? Chrome 65 fully supports ES6 module system.

推荐答案

这是一个可行的示例

file1.mjs

function log1() {
  console.log('log1');
}
function log2() {
  console.log('log2');
}
export { log1, log2 };

file2.mjs ,您必须明确编写.mjs扩展名

file2.mjs you must explicitly write .mjs extension

import { log1, log2 } from './file1.mjs';

log1();
log2();

index.html 通知属性 type ="module"

<body>
    <script type="module" src="file2.mjs"></script>
</body>

然后,您需要一个静态服务器来摆脱CORS块.

Then you need a static server to get rid of CORS block.

$ yarn global add serve
$ serve ./

最后转到http://localhost:5000,它将运行

更新:建议对模块使用.mjs文件扩展名而不是.js

Update: It is recommended to use .mjs file extension for modules instead of .js

这篇关于导入在Chrome中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆