随着 Typescript
愈来愈流行,我也开始随大流使用 ts
把以前用造的轮子从新造一遍。我在打包工具上纠结了一会,是 webpack
仍是 gulp
好呢。最终,我选择了 Rollup.js
。(没用过 Rollup
老是充满期待的)javascript
那就敲定使用 Rollup
+ Typescript
+ jest
来造轮子。java
我已经配置好的快速开始项目rollup-starter-ts
:github.com/zenoslin/ro…node
Rollup 是一个 JavaScript 模块打包器,正如他的官方文档所说:webpack
Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.git
而我就会想,那他跟 webpack
有什么区别呢?阅读文档知道他并不支持代码拆分和时态的动态导入。github
因此若是须要构建的是网站应用,可能 webpack
会比 Rollup
更合适。到这里我就能够把它理解为它是一个更专一 js
库的打包工具。web
安装 rollup
typescript
$ npm install --save-dev rollup
复制代码
安装完后,咱们先写一下配置文件 rollup.config.js
npm
// ./`rollup.config.js`
export default {
input: "./src/main.js",
output: [
{
format: "cjs",
file: "lib/bundle.cjs.js"
},
{
format: "es",
file: "lib/bundle.esm.js"
}
]
};
复制代码
让咱们来尝试一下打包,新建一个 js
文件json
// ./src/main.js
let version = "0.0.1";
export default () => {
return `this version is ${version}`;
};
复制代码
在 package.json
中加入
"scripts": {
"build": "rollup -c"
}
复制代码
运行打包
$ npm run build
./src/main.js → lib/bundle.cjs.js, lib/bundle.esm.js...
created lib/bundle.cjs.js, lib/bundle.esm.js in 32ms
复制代码
这时候咱们就成功的吧main.js打包成了两个版本 ES6
和 CommonJS
。
接下来咱们要让 rollup
支持打包 ts
安装 typescript
$ npm install --save-dev rollup-plugin-typescript typescript tslib
复制代码
安装 sourcemaps
$ npm install --save-dev rollup-plugin-sourcemaps
复制代码
在 rollup
的配置中添加插件
// ./`rollup.config.js`
import typescript from "rollup-plugin-typescript";
import sourceMaps from "rollup-plugin-sourcemaps";
export default {
input: "./src/main.ts",
plugins: [
typescript({
exclude: "node_modules/**",
typescript: require("typescript")
}),
sourceMaps()
],
output: [
{
format: "cjs",
file: "lib/bundle.cjs.js",
sourcemap: true
},
{
format: "es",
file: "lib/bundle.esm.js",
sourcemap: true
}
]
};
复制代码
将 main.js
文件改成 main.ts
let version: string = "0.0.1";
export default (): string => {
return `this version is ${version}`;
};
复制代码
打包文件
$ npm run build
./src/main.ts → lib/bundle.cjs.js, lib/bundle.esm.js...
created lib/bundle.cjs.js, lib/bundle.esm.js in 65ms
复制代码
到这里咱们就大功告成了,能够开始尽情地造轮子了!
可是既然是造轮子怎么能缺乏测试框架呢。
咱们须要添加 jest
并让它支持 ts
安装 jest
和其 ts
依赖
$ npm install --save-dev jest ts-jest @types/jest
复制代码
添加 jest
的配置文件 jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node"
};
复制代码
添加 test
文件夹,并添加文件 main.spec.ts
import Main from "../src/main";
test("version is 0.0.1?", () => {
const test = Main;
expect(test()).toBe("this version is 0.0.1");
});
复制代码
在 package.json
中加入 test
脚本
"scripts": {
"build": "rollup -c",
"test": "jest --no-cache"
}
复制代码
执行测试
$ npm run test
PASS test/main.spec.ts
√ version is 0.0.1? (6ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.739s
Ran all test suites.
复制代码
nice!这下咱们功德圆满能够尽情的造轮子了!