用rollup打包ts

8,165 阅读1分钟

1.全局编译TS文件

全局安装 typescriptTS进行编译

npm install typescript -g

tsc --init 生成tsconfig.json文件

tsc 可以将ts文件编译成js文件

tsc --watch 监控ts文件变化生成js文件

2.配置 webpack 环境

npm init -y 初始化配置

tsc --init 生成tsconfig.json文件

建一个rollup.config.js文件

安装依赖

npm i rollup typescript rollup-plugin-typescript2 @rollup/plugin-node-resolve rollup-plugin-serve

建src文件夹,在src文件夹下建 index.ts文件

rollup.config.json

import { nodeResolve } from '@rollup/plugin-node-resolve';
import ts from 'rollup-plugin-typescript2'
import serve from 'rollup-plugin-serve'
import path from 'path'export default {
    input:'src/index.ts',
    output:{
        file: path.resolve(__dirname,'dist/bundle.js'),
        // global: 弄个全局变量来接收
        // cjs: module.exports
        // esm: export default
        // iife: ()()
        // umd: 兼容 amd + commonjs 不支持es6导入
        format: 'iife',
        sourcemap: true, // ts中的sourcemap也得变为true
​
    },
    plugins:[  // 这个插件是有执行顺序的
        nodeResolve({
            extensions:['.js', '.ts']
        }),
        ts({
            tsconfig: path.resolve(__dirname, 'tsconfig.json')
        }),
        serve({
            port: 3000,
            contentBase:'', // 表示起的服务是在根目录下
            openPage: '/public/index.html' , // 打开的是哪个文件
            open: true // 默认打开浏览器
        })
    ]
}

tsconfig.json 中的 module 和 sourcemap 需要改变

"module": "ESNext",
"sourceMap": true,

建public文件夹 建立 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="/dist/bundle.js"></script>
</body>
</html>

配置命令

"scripts": {
    "dev": "rollup -cw"
  },

执行命令

npm run dev