记录的初衷:经常忘记配置项,反复需要找资料或者找以前的项目,先写个最简单的配置
创建项目目录
mkdir my-rollup
package.json初始化并修改
pnpm init
package.json
"scripts": {
"serve": "rollup -c -w",
"build": "rollup -c"
},
安装rollup和ts解析器
pnpm add rollup rollup-plugin-typescript2 -D
创建本地入口文件src/index.ts
js
const Hello = () => {
console.log('Hello, world!')
}
export default Hello;
rollup配置
js
import { defineConfig } from "rollup";
import typescript from "rollup-plugin-typescript2";
import path from "path";
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default defineConfig([
{
input: "src/index.ts", //入口文件
output: [
{
file: path.resolve(__dirname, "lib/main.js"),
format: "cjs",
name: "main.cjs",
},
{
file: path.resolve(__dirname, "./lib/main.umd.js"),
format: "umd", // 打包成UMD模块
name: "Hello" // 打包成UMD模式,需提供name
},
{
file: path.resolve(__dirname, "./lib/main.iife.js"),
name: "Hello",
format: "iife" // iife 表示立即执行函数
}
],
plugins: [
typescript(),
]
},
]);
tsconfig.json
配置项不明白的可以看这里www.tslang.cn/docs/handbo...
tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"outDir": "dist",
"baseUrl": "./",
"rootDir": "./src"
},
"exclude": ["node_modules", "dist"]
}
尝试打包cjs、umd和iife格式文件
pnpm build
umd和iife在项目中引入打包后的文件,将在windows中能找到Hello变量
创建exemple/index.html
index.html
<!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>
<body>
<script type="text/javascript" src="../lib/main.umd.js"></script>
</body>
</html>
插件Live Server运行index.html
打开服务后,控制台输入Hello(),将输出Hello, world!