Search code examples
node.jsgulp

Passing an argument to npm run script


I am creating a script in npm package.json.

The script will run yeoman to scaffold my template and then I want to run a gulp task to do some more stuff to a specific file (inject using gulp-inject)

The npm task looks like this:

"scaffolt": "scaffolt -g scaffolt/generators template && gulp inject"

Now, i need to be able to call the command from the command line giving a name to my template.

The command I need to run is the following:

npm run scaffolt {templateName}

but if I do this, then I try to run a gulp task called the same as the typed {templateName}.

A quick example: If I run npm run scaffolt myTemplate then the second part of this will try to run a task called gulp myTemplate, failing.

Is there any way to pass the {myTemplate} name as an argument to the second part of the script so that it can be used in the gulptask?

The gulp task currently only console.log the process.argv.


Solution

  • You can pass arguments to the npm run-script. Here is the documentation.

    Make gulp tasks for these operations.

    //gulpfile.js
    const gulp = require('gulp');
    const commandLineArgs = require('command-line-args');
    const spawn = require('child_process').spawn;
    
    gulp.task('inject', ['scaffolt'], () => {
      console.log('scaffolt complete!');
    });
    gulp.task('scaffolt', (cb) => {
      const options = commandLineArgs([{ name: 'templateName' }]);
    
     //use scaffolt.cmd on Windows!
     spawn('scaffolt', ['-g', 'scaffolt/generators', options.templateName])
        .on('close', cb);
    });
    

    And in your package

    //package.json
    "scripts": {
        "scaffolt": "gulp inject "
    }
    

    And to run it npm run scaffolt -- --templateName=something

    Tip: npm run-script appends node_modules/.bin directory in the PATH so we can spawn executables just like they are on the same folder!