有时是想要尝试或者学习某个包的时候会遇到这种情况,想要简单地使用node_modules中的包,又不想用脚手架起一个项目时,想要直接用html来运行。
比如这是一个引用three.js的demo
直接写script标签里
在script中写上type="module",就可以使用import引入包了。但注意需要相对路径引用到具体文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script type="module">
import * as THREE from './node_modules/three/build/three.module.js';
// ...
</script>
<body></body>
</html>
写单独的js文件里
如果想要将代码写在单独的文件里,则需要写一个<script type="importmap">来进行映射
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script type="importmap">
{
"imports": {
"three": "./node_modules/three/build/three.module.js",
"three/addons/": "./node_modules/three/examples/jsm/"
}
}
</script>
<script src="./demo.js" type="module"></script>
<body></body>
</html>
js文件就可以像一般的脚手架中那样写了
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// ...
这其实有点像第三方包中package.json中的exports配置项。我们之所以能这样引用文件也是因为它的存在
这是three.js的package.json的exports部分
{
// ...
"exports": {
".": {
"import": "./build/three.module.js",
"require": "./build/three.cjs"
},
"./examples/fonts/*": "./examples/fonts/*",
"./examples/jsm/*": "./examples/jsm/*",
"./addons/*": "./examples/jsm/*",
"./src/*": "./src/*",
"./nodes": "./examples/jsm/nodes/Nodes.js"
},
}
使用打包器打包
其实应该这才是正统方法,因为npm一般就是配合打包器使用的。经过打包后,依赖文件会导入到代码中,就不会存在依赖丢失的情况了。
这里用Rollup打包
在根目录下创建rollup.config.mjs,注意要安装插件@rollup/plugin-node-resolve
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default{
input: 'demo.js',
output: {
file: 'bundle.js',
format: 'cjs',
name: 'bundle'
},
plugins: [nodeResolve()]
}
然后运行
rollup -c
之后就会在根目录下生成一个bundle.js,直接在<script src="./demo.js" type="module"></script>标签引用就好