Bootstrap your next project with npm init

With latest npm versions you can trigger npx with npm init.

Try it out with:

npm init react-app

Basically behind the scene npm init will run npx create-react-app

Base on that knowledge, let's create a bootstrapper package and deploy it to the npm registry.

The bootstrapper I decided to create is for open source projects.

Features:

  • Run git init
  • Create license file
  • Create git ignore file
  • Create CODE_OF_CONDUCT.md
  • Run npm init -y
  • Add initial git commit.

The code: (github)

#!/usr/bin/env node
const exec = require("child_process").exec;

const run = cmd =>
  new Promise((resolve, reject) => {
    exec(cmd, (error, stdout, stderr) => {
      if (error !== null) {
        reject(error);
      }
      resolve(stdout);
    });
  });

const commands = ({
  license = "MIT",
  name = "Default",
  email = "[email protected]"
}) => [
  `git init`,
  `npx license ${license} -o "${name}" > LICENSE`,
  `npx gitignore node`,
  `npx covgen "${email}"`,
  `npm init -y`,
  "git add -A",
  'git commit -m "Initial commit"'
];

const main = async () => {
  try {
    let config = await run("npm config list --json");
    config = JSON.parse(config);
    let [name, email, license] = [
      config["init.author.name"],
      config["init.author.email"],
      config["init.license"]
    ];

    if (!(name && email && license)) {
      console.log(`
      Default value is not set.
      please use the below code to set the values.

      npm set init.author.name "Your name"
      npm set init.author.email "[email protected]"
      npm set init.author.url "https://your-url.com"
      npm set init.license "MIT"
      npm set init.version "0.0.1"
      `);
      return;
    }

    const _commands = commands({ name, email, license });
    for (let i = 0; i < _commands.length; i++) {
      const cmd = _commands[i];
      console.log(cmd);
      const output = await run(cmd);
      console.log(output);
    }
  } catch (error) {
    console.error(error);
  }
};

main();

Let's pick a name for our package, we learned we need to prefix the name with create- and we are going to create package for open source project so the obvious name is going to be create-open-source.

For those who didn't try to publish packages to the npm registry, you should sign up on npmjs.com and try npm publish in your project folder, make sure the name is unique.

Now let's try it out:

mkdir new-project
cd new-project
npm init open-source 

Nir Adler

Nir Adler