Published on

Building and Running a Single File With Babel

Authors

Today I wanted to add a script to my package.json file that ran against my running server. The script used axios to hit some endpoints on my running server.

To set it up I first made a directory called scripts in my project's src folder (the name of the directory is irrelvant). I then created my script file (lets call it migrateSampleDate.js) which looked like the following:

import axios from 'axios'

migrateSampleData.migrate = async function () {
  const httpClient = axios.create({
    baseURL: 'http://localhost:3001',
    timeout: 1000,
  })

  const data = [
    //...
    //your migration data here as separate json objects
    {
      name: 'John',
      surname: 'Smith',
    },
    {
      name: 'Jane',
      surname: 'Doe',
    },
  ]

  myData.forEach(async (data) => {
    httpClient.post('/client', person)
  })
}

migrateSampleData.migrate()

module.exports = migrateSampleData

I then added @babel/node to my package.json file:

yarn add -D @babel/node

In my package.json I added the following to the scripts section:

...
"scripts": {
  "run-single-file": "babel-node --presets @babel/env ./path/to/file/in/your/project.js"
},
...

This can be run by first starting the server:

yarn start

Then in another shell running:

yarn migrate

babel-node is meant to behave like babel-cli but does not 100%. For example normal babel uses --presets env while with babel-node you need to use --presets @babel/env. To be safe I made this single file use as few dependencies as possible and as simple as possible.