第一步报错
Uncaught SyntaxError: Cannot use import statement outside a module
错误说明:非模块无法使用import
源代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="charset" content="iso-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>es6测试</title>
</head>
<script>
import STATES from './states.js';
let oTest = {
[STATES.states1]() {
console.log('start')
}
}
oTest[STATES.states1]()
</script>
<body>
</body>
</html>
//states.js
export const oStates = {
states1: 'start',
states2: 'doing',
states3: 'end'
}
解决方案:html文件中用import引入模块会被识别为非模块文件,将script标签type属性添加为<script type="module">
第二步报错
Access to script at 'file:///D:/YNY/gitRepository/ts_study/states.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
错误说明:脚本被跨域拦截,由于跨域协议仅支持
http,data,chrome,chrome-extension,chrome-untrusted,https,而当前类型为file
源代码如下
//...
<script type="module">
import STATES from './states.js';
let oTest = {
[STATES.states1]() {
console.log('start')
}
}
oTest[STATES.states1]()
</script>
//...
解决方案:利用服务器方式启动页面。由于采用的是VScode开发,此处下载扩展插件Live Server,安装完成右键选择以本地服务器方式打开页面
第三步报错
Uncaught SyntaxError: The requested module './states.js' does not provide an export named 'default'
错误说明: 该引入模块没有名为default的默认导出模块
解决方案:因为此处import导入的时候没有采用大括号导入对应模块的形式,import会默认以default模块去导入,而export导出的时候并没有采用默认导出,而是变量导出的形式,所以无法找到default模块,只需要进行对应的修正
源代码如下
- 方案1:
采用export-import,需要注意,import命令接受一对大括号,里面指定要从其他模块导入的变量名。大括号里面的变量名,必须与被导入模块对外接口的名称相同,可以用as进行变量名的自定义;同理这一步放在export导出同样成立
//states.js
export const oStates = {
states1: 'start',
states2: 'doing',
states3: 'end'
};
//...
<script type="module">
import {oStates as STATES} from './states.js';
let oTest = {
[STATES.states1]() {
console.log('start')
}
}
oTest[STATES.states1]()
</script>
//...
- 方案2:
采用export default-import:
export default命令用于指定模块的默认输出,一个模块只有一个默认输出,而此时import命令接收到的就是export导出的唯一输出default,所以import直接用变量接收默认导出模块即可,无需大括号
//states.js
const oStates = {
states1: 'start',
states2: 'doing',
states3: 'end'
};
export default oStates;
//...
<script type="module">
import STATES from './states.js';
let oTest = {
[STATES.states1]() {
console.log('start')
}
}
oTest[STATES.states1]()
</script>
//...
至此代码终于运行了起来
寥寥几行代码想要运行,却遇上一环又一环的错误,不知道是幸运还是不幸。