gulp+rollup结合打包自己的TS/JS库

由于项目需要,网上找了不少资料,总结了一套适合项目的打包流程,把ts代码打包成js库


首先是gulpfile.js文件,直接贴上代码:

const gulp = require('gulp')
const rollup = require('rollup')
const clean = require('gulp-clean')
const rename = require("gulp-rename");
const uglify = require('gulp-uglify-es').default;

const rollupTypescript = require('rollup-plugin-typescript2')

gulp.task('clean', function () {
    return gulp
        .src('dist', { read: false, allowEmpty: true })
        .pipe(clean('dist'));
});



gulp.task('clean-js', function () {
    return gulp
        .src('dist/**/*.js', { read: false })
        .pipe(clean('*.js'));
});


gulp.task("build", async function () {
    const subTask = await rollup.rollup({
        input: "src/XH.ts",
		output: {
			file: 'dist/XHLib.js',
			format: 'umd', //iife
            extend: true,
			name: 'XH'
		  },
        plugins: [
            rollupTypescript()
        ]
    });
	
	await subTask.write({
            file: 'dist/XHLib.js',
			format: 'umd', //iife
            extend: true,
			name: 'XH'
        });
});

 gulp.task("uglify", function () {
     return gulp.src("dist/*.js")
         .pipe(rename({ suffix: '.min' }))
         .pipe(uglify(/* options */))
         .pipe(gulp.dest("dist/"));
 });

gulp.task('default'
    , gulp.series(
        gulp.parallel('clean'),
        gulp.parallel('clean-js'),
        gulp.parallel('build'),
        gulp.parallel('uglify')
    )
)


然后是package.json

{
  "name": "XHLib",
  "version": "1.0.0",
  "description": "",
  "main": "XHLib.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "SixSir",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^3.8.3",
    "gulp": "^4.0.2",
    "gulp-clean": "^0.4.0",
    "gulp-rename": "^2.0.0",
    "gulp-uglify-es": "^2.0.0",
    "rollup": "^2.0.6",
    "rollup-plugin-typescript2": "^0.26.0"
  }
}


最后是tsconfig.json

{
  "compilerOptions": {
    "module": "es6",
    "target": "es6",
    "noEmitHelpers": false,
    "sourceMap": false,
    "declaration": true,
    "noImplicitReturns":false,
    "allowUnreachableCode":false
  },
  "exclude": [
    "node_modules"
  ]
}


代码放在同目录下的src文件夹就好

3个必要的配置文件准备好了后,运行: 

  1. npm install

  2. gulp

  3. 生成的d.ts 和 js文件会在dist目录下

暂无评论

发布评论

分享:

支付宝

微信