how to run node / babel script directly in command

2020-02-05 08:04发布

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

6条回答
霸刀☆藐视天下
2楼-- · 2020-02-05 08:28

node ./node_modules/babel-cli/bin/babel-node.js --presets env app.js

EDIT

Updated as requested by OP.

查看更多
forever°为你锁心
3楼-- · 2020-02-05 08:32

Great gugley mugleys! This was way harder than it should have been.

See here for docs. TLDR;

Babel > version 7.0 has to go in your package.json to run from command line.

npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node 

npx babel-node --presets @babel/preset-env imports/test.js 
查看更多
beautiful°
4楼-- · 2020-02-05 08:33

You can run the app.js file from node by telling it about babel-node first:

node ./node_modules/.bin/babel-node app.js

with the following .babelrc file at the root project

{"presets": ["@babel/preset-env"]}

查看更多
倾城 Initia
5楼-- · 2020-02-05 08:35

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
查看更多
爷的心禁止访问
6楼-- · 2020-02-05 08:45

Babel node has a bin registered so an executable is generated on install inside the node_modules/.bin directory.

You may run it simply by typing.

node_modules/.bin/babel-node --presets env app.js

Which accomplishes the same thing as the longer node or the alternate npx versions.

查看更多
够拽才男人
7楼-- · 2020-02-05 08:47

Install @babe/node globally-

npm i -g @babel/node

then babel-node command becomes available in your terminal. So, you can run -

babel-node --presets env app.js

Btw, it should be used in dev environment only, never recommended for production as it's unnecessarily heavy with high memory usage.

查看更多
登录 后发表回答