在html中引入type='module'的script
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="module" src="main.js"></script>
<script type="module" src="message.js"></script>
</body>
</html>
//message.js
function sendMsg() {
console.log('hello')
}
const msg = 'this is msg '
export {
sendMsg,
msg
}
//main.js
//第1种import方式
import {msg,sendMsg} from "./message.js";
console.log(msg) //this is msg
sendMsg() //hello
//第2种import方式
import * as file from "./message.js";
console.log(file.msg)
file.sendMsg()
注意:import路径要写完整,跟webpack和node有差别
// 被支持的几种路径写法
import module from 'http://XXX/module.js'
import module from '/XXX/module.js'
import module from './XXX/module.js'
import module from '../XXX/module.js'
// 不被支持的写法
import module from 'XXX'
import module from 'XXX/module.js'