Rollup 构建TS项目

Rollup 构建TS项目

项目结构

tsconfig.json

tsc --init

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6tO01duX-1667465752105)(/Users/chenzhonghai/Desktop/截屏2022-10-06 19.33.04.png)]

package.json


{
  "name": "study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bulid":"rollup -c",
    "dev":"rollup -c -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "cross-env": "^7.0.3",
    "rollup-plugin-livereload": "^2.0.5",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-replace": "^2.2.0",
    "rollup-plugin-serve": "^1.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.31.1",
    "typescript": "^4.5.5"
  }
}

npm install -y

rollup.config.js

import path from 'path'
import ts from 'rollup-plugin-typescript2'
import server from 'rollup-plugin-serve'
import livereload from 'rollup-plugin-livereload'
import { terser } from 'rollup-plugin-terser'
export default{
    input:"./src/index.ts",

    output:{
        file:path.resolve(__dirname,'./lib/index.js'),
        format:'umd',
        sourcemap:true
    },
    plugins:[
        ts(),
        livereload(),
        terser(),
        server({
            open:true,
            port:1988,
            openPage:"/public/index.html"
        })
    ]
}

最后将tsconfig.js的module改为ES2015

Rollup打包TypeScript项目时,默认情况下,它会移除所有的console.log等浏览器内置函数,以优化生产环境下的体积。如果你想在构建后的代码中保留这些console调用,可以采取以下步骤进行配置: 1. **安装插件**:首先,你需要安装`rollup-plugin-node-resolve` 和 `commonjs` 插件,它们可以帮助处理Node.js的模块导入,并允许保留console调用: ``` npm install rollup-plugin-node-resolve commonjs --save-dev ``` 2. **添加配置**:在`rollup.config.js`文件中,编写配置部分,确保包含了这两个插件: ```javascript import resolve from 'rollup-plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; export default { input: 'src/index.ts', // 输入文件路径 output: { file: 'dist/bundle.js', // 输出文件路径 format: 'cjs', // 使用CommonJS格式以保持原样 }, plugins: [ resolve(), commonjs({ include: ['node_modules/**'], // 包含Node.js模块 }), ], }; ``` 在`commonjs`选项的`include`属性中,明确指定要保留console调用的模块路径,通常是`node_modules`下的所有模块。 3. **启用devServer**:如果你还想要在开发环境中看到console输出,可以配置一个dev服务器,如`rollup-plugin-serve` 和 `rollup-plugin-livereload`: ```javascript import serve from 'rollup-plugin-serve'; import livereload from 'rollup-plugin-livereload'; ... // 其他配置 plugins: [ ..., serve({ contentBase: './dist', // 指定服务器内容基础目录 port: 5000, // 端口 }), livereload({ watch: 'dist' }), // 实时刷新 ] ``` 现在,你应该能够保留`console`调用并在开发和生产环境中正常使用它们。不过请注意,这可能会增加最终生成的JavaScript文件大小。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值