What is the best way to create multiline scripts within npm scripts?

Here is how my package.json is structured:

{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "lint": "./node_modules/eslint/bin/eslint.js --format \"./node_modules/eslint-friendly-formatter/index.js\" .",
    "build:server": "./node_modules/babel-cli/bin/babel.js . -d dist/server --ignore node_modules,dist,client,public,webpack*"
  }
}

The commands lint and build:server in the script section above are quite hard to read, so I am considering breaking them into multiple lines.

I attempted using \, but it resulted in errors like this:

npm ERR! Failed to parse json
npm ERR! Unexpected token ' ' at 11:80
npm ERR! :server": "./node_modules/babel-cli/bin/babel.js . -d dist/server \
npm ERR!                                                                   ^

Is there a way for me to achieve this without errors? Or should I create another bash file such as build.sh and call it in npm scripts with ./build.sh server?

Answer №1

You have the ability to link separate tasks together.

For instance:

"scripts": {
    "lint-jshint": "jshint --verbose --show-non-errors ./src/main/js",
    "lint-eslint": "eslint ./src/main/js ./src/test/js",
    "lint-csslint": "csslint ./src/main/js",

    "lint": "npm run -s lint-jshint & npm run -s lint-eslint & npm run -s lint-csslint",

    "pretest": "rimraf ./build/reports/tests && mkdirp ./build/reports/tests && npm run -s lint",
    "test": "karma start ./src/test/resources/conf/karma.conf.js",
    ...

Check out this interesting blog I found back then:

Answer №2

That action is not allowed.

The code snippet can be found in read-json.js, located within the package

node_modules/npm/node_modules/read-package-json
. It is used in run-script.js to run either $ npm run-script ~~ or its alias $ npm run ~~.

function scriptpath (file, data, cb) {
  if (!data.scripts) return cb(null, data)
  var k = Object.keys(data.scripts)
  k.forEach(scriptpath_, data.scripts)
  cb(null, data)
}

function scriptpath_ (key) {
  var s = this[key]
  // This action is restricted and may cause issues
  if (typeof s !== 'string') return delete this[key]

  var spre = /^(\.[\/\\])?node_modules[\/\\].bin[\\\/]/
  if (s.match(spre)) {
    this[key] = this[key].replace(spre, '')
  }
}

The variable key in scriptpath_ represents something like "build:server" in your code.

The value of this[key] is similar to

"./node_modules/babel-cli/bin/babel.js . -d dist/server --ignore node_modules,dist,client,public,webpack*"
in your code.

Therefore, ensure that any code you input in package.json is of type string to prevent errors unless you are contributing to the npm/read-package-json package.

Answer №3

Another popular option is creating an npm command that points to a local bash script (which provides more flexibility).

For example:

# package.json
{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "lint": "./node_modules/eslint/bin/eslint.js --format \"./node_modules/eslint-friendly-formatter/index.js\" .",
    "build:server": "./build-server.sh"
  }
}
# build-server.sh
#!/bin/bash

./node_modules/babel-cli/bin/babel.js . \
  -d dist/server \
  --ignore node_modules,dist,client,public,webpack*

NOTE: Ensure you have permission to execute the file; otherwise, you may encounter permission errors.

sudo chmod 755 'build-server.sh'

Refer to: Run script on mac prompt "Permission denied"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for transferring information obtained from an API to my custom HTML page

As a novice in web development, I recently created a simple weather report website using the OpenWeather API. While I successfully fetched data from the API, I encountered an issue trying to display this data on my HTML page. Despite utilizing DOM manipu ...

Tips for incorporating the ternary operator in JSX of a React component while utilizing TypeScript?

I am looking to implement a conditional rendering logic in React and TypeScript, where I need to return null if a specific condition is met, otherwise render a component using a ternary operator. Here is the code snippet I currently have: {condition1 && ...

Sending a request to a JSON file using Ajax

I have 2 questions: 1. I am trying to run this file, but it is not giving any errors or showing results. Please help me identify the problem. 2. I added a dropdown menu in my HTML file, but I'm unsure how to use it to display a list of names. Any sugg ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Display the entire dataset retrieved from MongoDB and utilize the doT.js templating engine for rendering

I am facing an issue with extracting data from mongodb and passing it to the view. Despite all my efforts, only one record out of 10000 is showing up instead of all of them. I believe I am very close to resolving this problem but unfortunately, I am stuck. ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

"Enhancing Your List: A Comprehensive Guide to Editing List Items with the Power of AJAX, jQuery, and

At the moment, I am able to edit a list item by clicking the 'Edit' link. However, I would prefer to simply click on the list item itself to initiate the editing process. This is the content of my _item.html.erb partial. In this case, each proj ...

Combining the power of ExpressJS with a dynamic blend of ejs and React for an

My current setup involves a NodeJS application with an Express backend and EJS for the frontend. The code snippet below shows an example route: router.get("/:name&:term", function(req, res) { Course.find({ courseName: req.params.name, courseTerm: req.p ...

Unable to retrieve data function properties within Vue.Js Component methods

Looking for some help with setting up a welcome message using an input field in Vue.js. I am trying to store the username in a data property called username: ''. However, when I attempt to access it within the methods, I receive an error stating ...

What is the best way to dynamically pass JSON object values to PHP?

Greetings, I am new to JSON and Ajax. Although my question may seem trivial, I believe that even the simplest inquiries are crucial in the learning process. My dilemma involves passing two parameters (giorno and periodo) via Ajax: For example: 'gior ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Holding off $ajax requests until specific code finishes executing

I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in t ...

Is the callback for a request always invoked?

When using the npm module request, I often encounter situations where some requests are not called back, leading to various issues. This has raised a question in my mind - is it expected for the request function to always callback? For instance, if my req ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Selenium - Activating a flash button

Currently, I am facing an issue while trying to load a URL using Selenium on Mozilla browser. The webpage contains a 'Login' button created in flash that I need to click on. I have explored the following resources: 1.How to click an element in Se ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...

The HTML Bootstrap collapse feature is not functioning correctly upon the initial button press

Could you assist me with implementing a bootstrap and javascript collapse feature? I have two collapsible cards. The first card should be visible initially, but then switch to the second card when clicked on a link. However, upon the first click, both card ...

Verify if the value in a textbox exceeds the number entered in an array of textboxes

My goal is to compare the value of a single text box, labeled as "totalmarkstoall", with multiple arrays of text boxes labeled as "marksscored". The JavaScript code below is set up to compare these values using a key up function. The issue I am facing is ...

Efficiently perform complex nested grouping using the powerful array

Hi, I'm currently facing difficulties while attempting to utilize the array.reduce() function in order to achieve correct grouping for a specific scenario: Here is my original array: { { descriptionFunction: "Change", processDate: "201 ...

Is it possible to create two header columns for the same column within a Material UI table design?

In my Material UI table, I am looking to create a unique header setup. The last column's header will actually share the same space as the previous one. Picture it like this: there are 4 headers displayed at the top, but only 3 distinct columns undern ...