Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

node.js - how to run node / babel script directly in command line?

My package.json looks like:

{
  "name": "99-nodetest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "babel-node --presets env app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "latest"
  }
}

The js script i want to run is app.js. I cannot run it directly using node app.js because app.js contains new language syntax.

Thus i have to run it through babel, using npm start, as per the start script defined above. No issues here.

My question is how to run the cmd directly in the command line, can it be done? something similar to:

npm run babel-node --presets env app.js

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can execute npm package binaries with npx.

Because Babel 7 always resolves plugins and presets relative to local project folder, you will have to install @babel/preset-env locally into the project.

npm i -D @babel/preset-env

After that the babel-node can be run with npx without installation into the project:

npx -p @babel/core -p @babel/node babel-node --presets @babel/preset-env app.js

If you install @babel/node into the project, npx will prefer project-local version.


In case of Babel 6 the command below can be used:

npx babel-node --presets env app.js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...