如何让npm包自动发布?

时间:2016-10-17 19:05:26

标签: npm continuous-integration teamcity

我需要使用TeamCity组织NPM包自动发布。我在一个git仓库里面有几个NPM包。当我推送更改时,我需要检测更改了哪些包,更新其版本,make commit&推送新版本并发布新包。是否有一些工具可以做到这一点?

1 个答案:

答案 0 :(得分:0)

以下是自动发布的代码,tou可以通过在TeamCity中创建任务来使用,也可以自己使用。别忘了npm安装所需的软件包。

const gulp = require('gulp');
const NodeGit = require("nodegit");
const bump = require("gulp-bump");
const semverUtils = require('semver-utils');
const npm = require('npm');
const spork = require('spork');

gulp.task('publish', function (done) {
    const pathToRepo = require("path").resolve("./");
    const args = require('yargs').argv;
    const nextVersion = args.version;

    NodeGit.Repository
        .open(pathToRepo)
        .then(repo => repo.getBranchCommit("master"))

        .then(lastCommit => {
            const repo = lastCommit.repo;
            const sign = NodeGit.Signature.default(repo);

            if (lastCommit.author().email() == sign.email()) {
                console.info('It looks like the last commit was done by CI');
                done();
                process.exit(0)
            }

            const currentVersion = require('./package.json').version;
            const semver = semverUtils.parse(currentVersion);

            if (nextVersion == null) {
                semver.patch++;
            } else {
                semver.patch = nextVersion;
            }

            const version = semverUtils.stringify(semver)

            return gulp.src('./package.json')
                .pipe(bump({ version }))
                .pipe(gulp.dest('./'))
                .on('end', () => {

                    repo
                        .createCommitOnHead(['package.json'], sign, sign, `Update UI lib version to v${version}`)
                        .then(commit => repo.createTag(commit, `v${version}`, ''))
                        .then(() => pushGit())
                        .then(() => console.info('Made commit with changed package.json and made push'), err => console.error(err))
                        .then(() => publishNpm())
                        .then(() => done())
                        .then(() => process.exit(0))
                });
        })
});

function pushGit() {
    console.info('Start commiting to GIT');

    return new Promise((resolve, reject) =>
        spork('git', ['push'], { exit: false })
            .on('exit:code', function (code) {
                if (code === 0) {
                    resolve();
                } else {
                    reject();
                }
            })
    )

}

function publishNpm() {
    console.info('Start publishing to NPM');

    return new Promise((resolve, reject) => {
        npm.load({}, err => {
            err && reject(err);

            npm.publish(err => {
                err && reject(err);
                resolve();
            });
        });
    })
}