错误原因:
在html文件中的script 标签引入了ES6模块,浏览器中打开该html文件。浏览器报错的原因是我们用了比较现代的es6的语法, 但是浏览器将它作为以前版本的js解析,所以出现问题,需要将他作为模块导入,script标签默认type="text/javascript",需要改为type="module"。
正确用法:
为了让 JavaScript 更模块化、更整洁以及更易于维护,ES6 引入了在多个 JavaScript 文件之间共享代码的机制。 它可以导出文件的一部分供其它文件使用,然后在需要它的地方按需导入。 为了使用这一功能, 需要在 HTML 文档里创建一个 type 为 module 的脚本。 例子如下:
例子1:
test.js
const test ={
template:``,
model:{}
}
export default test
index.html
<script type="module">
import test from '../test.js'
</script>
例子2:
test.js
export const add = (x, y) => {
return x + y;
}
index.html
<script type="module">
import { add } from './test.js';
console.log(add(1,2)); // 打印出3
</script>