使用Rollup搭建TypeScript环境
· 阅读需 3 分钟
使用 Rollup 搭建 TypeScript 的体验环境,避免每次修改都要使用 tsc 重新编译。
1. 初始化项目
mkdir -p rollup-project/src
cd rollup-project
npm init -y
安装依赖:
pnpm add -D typescript rollup @rollup/plugin-typescript @rollup/plugin-node-resolve rollup-plugin-serve
- @rollup/plugin-typescript:集成 ts
- @rollup/plugin-node-resolve:node 解析
- rollup-plugin-serve:启动开发服务器
2. 创建 tsconfig.json 文件
npx tsc --init
然后修改模块化配置:将"module": "commonjs"
改为"module": "esnext"
3. 配置 package.json 文件
{
"type": "module",
"scripts": {
"dev": "rollup -c -w"
}
}
-c
表示执行 rollup.config.js 文件,-w
表示监听文件变化。
4. 构建路径变量
前面已经配置了"type": "module"
,所以没有__dirname
和__filename
,需要自己构建这两变量。
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
const __filename = fileURLToPath(import.meta.url); // 当前文件的绝对路径
const __dirname = dirname(__filename); // 当前文件所在的文件夹的绝对路径
import.meta.url
是 ESModule 的一个属性,表示当前模块的 URL。如:file:///Users/zgh/project/rollup.config.js?1730857880251
,通过 fileURLToPath
可以将其转换为:/Users/zgh/porject/rollup.config.js
5. 配置开发服务器
在根目录下创建public/index.html
文件,用于展示的页面。在里面引入打包后的 js 文件:<script src="/dist/bundle.js"></script>
创建 scr/index.ts
文件,用于测试。内容如下:
const a: string = 'hello world';
console.log(a);
注意:如果不打印 a 的值,打包后的文件里没有 a 的定义,内容是空的。因为 Tree Shaking 优化。
配置后就可以运行 pnpm dev
,然后打开浏览器访问http://localhost:3001/public/index.html