JavaScript中的export
JavaScript中的export和import是常见的报错。其中,一种常见错误是Uncaught SyntaxError: Cannot use import statement outside a module。这是因为script标签默认使用JavaScript语言,使用ES6的语法会发生解析错误,需要在script标签中加入type=”module”,具体如下:

<script type="module"> import Rotation from '../js/ui.js' Rotation(); </script>
这段代码中,type=”module”能够避免代码解析错误。
JavaScript中的import
除了export,JavaScript中的import也常见于错误信息。例如Uncaught SyntaxError: The requested module ‘../js/ui.js’ does not provide an export named ‘default’。现在介绍如何处理这个错误。
在使用export时,可以使用export default暴露目标。在使用import时,需要通过”{}”以对象的形式进行引用,而export default只能向外暴露一个目标,因此不需要使用{}。例如:
<script type="module">
// 改为export default
export default{
Rotation: function(){
let lbt = document.querySelectorAll('.zh-lbt');
for (let i = 0; i < lbt.length; i++) {
let lbtNum = Number(lbt[i].getAttribute('num'))||1
console.log(lbtNum);
}
}
}
import {Rotation} from '../js/ui.js'
Rotation.Rotation();
</script>
在上述代码中,使用了export default向外暴露目标,在import时不需要使用{}。
结尾
文中介绍了JavaScript中的export和import,分别针对了两种常见的报错,并给出了解决方案。如果还有其他问题或者疑问,欢迎联系我们。
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/5760.html
