Javascript 尝试在 Chrome 扩展程序中导入模块时出现“意外标识符”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48040258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:00:13  来源:igfitidea点击:

'Unexpected identifier' when trying to import modules in Chrome extension

javascriptgoogle-chrome-extensionmodule

提问by Kim Nedergaard Clausen

I'm developing a Chrome extension that will make use of some background scripts. I thought it would be interesting to make use of modules since Google recently added native support for them.

我正在开发一个 Chrome 扩展程序,它将使用一些后台脚本。我认为使用模块会很有趣,因为 Google 最近为它们添加了原生支持。

However, I'm getting a 'Uncaught SyntaxError: Unexpected identifier' error when I'm attemtping to import a module. The errors points to the line of code where the import is written. Here's an example:

但是,当我尝试导入模块时,我收到了“Uncaught SyntaxError: Unexpected identifier”错误。错误指向写入导入的代码行。下面是一个例子:

In main.js:

在 main.js 中:

import test from './test.js';

In test.js:

在 test.js 中:

export default function test () {
  console.log('this is a test.');
}

I've tried various other formats, but none of them works. Interestingly, Chrome's newest import('file.js') function works just fine. However, I'm looking for a way to import modules without using promises.

我尝试了各种其他格式,但没有一个有效。有趣的是,Chrome 最新的 import('file.js') 函数运行良好。但是,我正在寻找一种无需使用承诺即可导入模块的方法。

Am I doing something wrong, or am I just not supposed to make use of modules in Chrome Extensions?

我做错了什么,还是我不应该使用 Chrome 扩展程序中的模块?

Thanks in advance.

提前致谢。

回答by Ankit Sinha

If you are getting an error shown below while using import (ES6 module).
enter image description here

如果您在使用导入(ES6 模块)时收到如下所示的错误。
在此处输入图片说明

You need to inform the browser by using the type="module"in the script tag you are using in the HTML file. Use this to link you js file in HTML

您需要type="module"通过在 HTML 文件中使用的脚本标记中使用来通知浏览器。用它来链接你的 HTML 中的 js 文件

<script type="module" src="./main.js"></script>

<script type="module" src="./main.js"></script>

回答by Kaibo

You should add type='module'to the main.jsimport line

您应该添加type='module'main.js导入行

look at this ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"

看看这个ES6 模块导入给出“Uncaught SyntaxError: Unexpected identifier”