一、创建项目
1、初始化项目
1、创建一个项目目录,进入该目录
2、执行 npm init -y
生成 package.json
3、执行 tsc --init
生成 tsconfig.json
2、安装依赖
(1)安装 typescript 和 rollup-plugin-typescript
npm install -D typescript rollup-plugin-typescript
(2)安装 rollup,我这里是全局安装
npm install rollup --global
可以用 rollup -v
查看安装版本
二、编译配置
(1)修改 tsconfig.json
{"compilerOptions": {"target": "ES5","module": "commonjs","strict": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"sourceMap": true,"outDir": "dist","baseUrl": ".","paths": {},"lib": ["dom", "dom.iterable", "esnext"]},"include": ["src"]
}
(2)根目录新建 rollup.config.js
import typescript from 'rollup-plugin-typescript';export default {input: 'src/main.ts',output: {file: 'dist/bundle.js',format: 'cjs'},plugins: [typescript(),],
};
(3)package.json 增加 script
注:-w 会监测文件修改重新打包
{"scripts": {"dev": "rollup -c -w --environment INCLUDE_DEPS,BUILD:development"},
}
(4)测试
新建 src/main.ts
const sname: string = "rollop";console.log(sname);
执行如下脚本:
npm run dev
如果生成 dist/bundle.js 则代表成功
若报错:
RollupError: Node tried to load your configuration file as CommonJS even though it is likely an ES module. To resolve this, change the extension of your configuration to ".mjs", set "type": "module" in your package.json file or pass the "--bundleConfigAsCjs" flag
则在 package.json 中 添加
"type": "module",