Search code examples
javascriptnode.jsnpmversion-controlcontinuous-integration

How to publish an NPM package from the CI build pipeline and still automate versioning?


I can't seem to see the forest behind the trees. I want to have a simple CI pipeline that builds and publishes an NPM package. I use appveyor, but I don't think my issue is specific to it. I simply want my CI script to be performing something like this:

git clone "https://git_repo_url" .
npm run build
npm run test
npm version patch --git-tag-version
npm publish -tag beta

The problem is:

  • If I don't do the npm version patch step, the publishing will fail with the feed already contains the package 'abc' at version 'x.y.z' error.

  • If I do that step, then I'd have to push the new commit (the version change) back to the git repo. Otherwise, it will fail as above next time me or someone else build it. Yet I don't feel like doing git push in the back-end pipeline would be the right thing.

  • Lastly, if this CI script just builds the NPM package without publishing it, how do I consume it in other projects which are depending on it?

What are the industry standard ways of doing this?

For instance, if I need to test a non-production feature version of my package with another project, should I make my CI script to patch the package's package.json with a generated, unique semver-compatible version (without commiting it), and then publish it with an npm tag that would match my git branch name? Is it a good idea?


Solution

  • I did it as below, in my javascript project.

    Note: get your key form .npmrc

    publish:
        image: <your project image>
        stage: publish
        script:
            - echo _auth=$NPM_PUBLSH_KEY >> .npmrc
            - echo email=<youremail> >> .npmrc
            - echo always-auth=true >> .npmrc
            # - cat .npmrc
            - npm version --no-git-tag-version $(npm view <yourProject>@latest version)
            - npm version --no-git-tag-version prerelease
            - npm publish
        dependencies:
            - build
    
    
    build:
        image: <your project image>
        stage: build
        script:
            - node --version
            - npm --version
            - npm ci
            - npm run build -- --watch=false
            - npm run build:prod