在html文件中使用npm 下载的包,比如vue,在使用import引入的时候会报错
<!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></body>
<script type="module">
import { createApp } from "vue";
console.log(createApp());
</script>
</html>
Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
因为在浏览器环境
中必须使用/
,./
或者../
来表示路径的,在平时项目开发中都是使用的webpack
或者vite
来进行开发,他们都是基于node.js
环境的,我们就想这样使用咋办?这时候就需要使用importmap了
<!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></body>
<script type="importmap">
{
"imports":{
"vue":"./node_modules/vue/dist/vue.esm-browser.js"
}
}
</script>
<script type="module">
import { createApp } from "vue";
console.log(createApp());
</script>
</html>
这样就能正常引入包了,这里的vue可以随便取名,abc也行,只要下面引入的名字和这里对应起来就行了