运行 来自 npm 脚本的 babel-cli 不工作

Running babel-cli from npm script not working

我按照说明 here 安装了 babel-cli。我将 "build": "babel src -d lib" 添加到我想要 运行 的目录中的 package.json。但是,在 运行ning 上,我收到此错误:

  npm run build

> ipfs-readme-standard@1.0.0 build /Users/richard/src/ipfs-readme-standard
> babel src -d lib

src doesn't exist

npm ERR! Darwin 14.5.0
npm ERR! argv "/Users/richard/.nvm/versions/node/v5.0.0/bin/node" "/Users/richard/.nvm/versions/node/v5.0.0/bin/npm" "run" "build"
npm ERR! node v5.0.0
npm ERR! npm  v3.5.2
npm ERR! code ELIFECYCLE
npm ERR! ipfs-readme-standard@1.0.0 build: `babel src -d lib`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the ipfs-readme-standard@1.0.0 build script 'babel src -d lib'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ipfs-readme-standard package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     babel src -d lib
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ipfs-readme-standard
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ipfs-readme-standard
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/richard/src/ipfs-readme-standard/npm-debug.log

我很茫然。不应该生成 src 吗? babeljs.io 上没有我遗漏的额外步骤。

Shouldn't src be generated?

这是包含您要转译的脚本的文件夹。如果它不存在,那么 babel 将抛出您发布的错误。

此外,请注意您链接到的页面底部的内容:

Pre-6.x, Babel enabled certain transformations by default. However, Babel 6.x does not ship with any transformations enabled. You need to explicitly tell it what transformations to run. The simplest way to do this is by using a preset, such as the ES2015 Preset.

这意味着即使你创建一个 src 目录并在其中放置一个包含 ES6 代码的文件,Babel 也会很高兴 运行,但输出将(几乎)与输入相同.


这是一个如何启动和运行 babel-cli 的快速示例。

创建项目,然后安装babel-cli包和ES2015预设:

mkdir babeltest && cd babeltest
touch package.json
npm install babel-cli babel-preset-es2015 --save-dev

下一次编辑 package.json:

{
  "name": "my-project",
  "version": "1.0.0",
  "scripts": {
    "build": "babel src -d lib"
  },
  "scripts": {
    "build": "babel --presets es2015 src -d lib"
  },
  "devDependencies": {
    "babel-cli": "^6.0.0"
  }
}

请注意,npm 脚本中的命令与 babel homepage 中的命令略有不同,因为我们告诉它使用已安装的预设。

接下来在src目录下制作一个文件:

mkdir src && cd src
touch main.js

在main.js中添加:

[1,2,3].map(x => x * x)

然后 运行 babel 通过 npm:

npm run build

并检查 lib/main.js

中的输出
"use strict";

[1, 2, 3].map(function (x) {
  return x * x;
});

当您的节点模块未安装时,您也会遇到此错误,如果您从互联网上下载代码并立即尝试 运行ning 代码,它会抛出上述错误,只是 运行

npm install

然后

npm run build // 或者其他命令应该有效

如果有人仍在寻找解决方案,请检查 .babelrc 是否丢失 如果是这样,只需创建一个新的 .babelrc 文件并将上面的代码片段粘贴到其中。

{
  "presets": ["es2015", "stage-0"]
}