我們知道,在script標簽中寫js代碼,或者使用src引入js文件時,默認不能使用module形式,即不能使用import導入文件,但是我們可以再script標簽上加上type=module屬性來改變方式。
- 使用方法如下:
- js引用js
//module.js
export default function test(){
return 'test...'
}
// index.js
import test from './module.js';
console.log(test())
- html頁面引用js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
// 方法 1 : 引入module.js,然后在script標簽里面調用
<script type="module">
import test from './module.js';
console.log(test())
</script>
// 方法 2 : 直接引入index.js,使用src引入
<script type="module" src="./index.js"></script>
</body>
</html>