【问题标题】:Babel doesn't work, returns CLI errorsBabel 不工作,返回 CLI 错误
【发布时间】:2016-11-24 14:14:28
【问题描述】:

我使用以下命令在我的项目中本地安装了 Babel:

npm install babel-cli babel-core babel-preset-es2015 --save-dev

这在 package.json 中为我提供了以下输出:

{
  "name": "my_project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "babel src -d lib"
  },
  "scripts": {
    "build": "babel --presets es2015 src -d lib"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.18.0",
    "webpack": "^1.13.3"
  },
  "dependencies": {
    "lodash": "^4.17.2"
  }
}

我不确定,但看起来它安装成功了。但是当我尝试运行 npm run babel 时,我得到:

npm ERR! Darwin 15.3.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "babel"
npm ERR! node v7.0.0
npm ERR! npm  v4.0.2

npm ERR! missing script: babel
npm ERR! 
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
nam ERR!     /Path/To/My/Project/npm-debug.log

为什么 Babel 不起作用?在 package.json 文件中包含:

【问题讨论】:

标签: npm webpack command-line-interface babeljs


【解决方案1】:

所以你运行npm run babel

上面写着npm ERR! missing script: babel

也许你的意思是:npm run build


需要思考的两件事:

  1. npm run

    这会从包的“脚本”对象运行任意命令。

  2. babel 不是package.json 中的脚本,而是将 ES6 转换为 ES5 的 JavaScript 转译器。

所以如果你运行npm run build,它将执行这里定义的build 命令:

  "scripts": {
    "build": "babel src -d lib"
  },

我还看到scripts 对象有一个重复

【讨论】:

    【解决方案2】:

    有多种方法可以运行已安装的 npm 可执行文件。

    最简单的方法是全局安装它。在您的情况下,您只需要 babel-cli 在命令行中可用。所以npm install -g babel-cli 就可以了。

    如果您只想在本地安装它,babel 可执行文件也可以在 node_modules/.bin/babel 上使用。但肯定是为了输入命令。

    您尝试的另一种方法是使用npm-run-scripts。在这种情况下,您必须在 package.json 中定义脚本。你已经有一个build 脚本,你可以像npm run build 一样运行它。所以对于npm run babel,你需要相同形式的脚本定义:

    "scripts": {
        "build": "babel src -d lib",
        "babel": "babel script.js --out-file script-compiled.js" // For example
    }
    ...
    

    这主要用于为您希望频繁运行的命令(如构建脚本)提供简写。

    您还可以使用以下语法为 npm 脚本提供其他参数:

    npm run babel -- --presets es2015

    请注意此处的额外--

    还有另一种选择,您可以全局安装一个包并从不同的项目链接到它:

    npm install -g babel-cli 并在您的项目目录中npm link babel-cli

    最常见的方法是在全局和本地安装可执行包(命令行界面)的最简单方法。

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2018-01-30
      相关资源
      最近更新 更多