Uncaught SyntaxError SyntaxError: Cannot use import statement outside a module
时间: 2023-10-18 18:32:03 浏览: 103
报错:Uncaught SyntaxError: Cannot use import statement outside a module 详解
Uncaught SyntaxError: Cannot use import statement outside a module 是一个JS错误。这个错误的原因是在非模块中使用了import语句。
为了解决这个错误,您可以将脚本的类型设置为module,页面中的script标签添加type="module"属性。例如,在index.html文件中可以这样编写脚本代码:
```
<script type="module">
import { add } from './test.js';
console.log(add(1,2)); // 打印出3
</script>
```
同时,确保导入的模块(test.js)也是一个ES6模块,需要使用export语句将需要导出的函数或变量暴露出来。例如,在test.js文件中可以这样编写代码:
```
export const add = (x, y) => {
return x + y;
}
```
通过以上方法,您可以解决Uncaught SyntaxError: Cannot use import statement outside a module错误,并且成功使用import语句在模块中导入其他脚本中的函数或变量。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [报错:Uncaught SyntaxError: Cannot use import statement outside a module 详解](https://download.csdn.net/download/weixin_38517095/14038442)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Uncaught SyntaxError: Cannot use import statement outside a module](https://blog.csdn.net/Amnesiac666/article/details/129103005)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文