简体   繁体   English

Babel-CLI 正确设置配置值

[英]Babel-CLI set config value correctly

I am trying to add a build command that uses babel CLI to transpile my ES6.我正在尝试添加一个使用 babel CLI 来转换我的 ES6 的构建命令。 I am having difficult pointing it correctly to babelrc.我很难将它正确指向 babelrc。

The file structure is roughly as follows:文件结构大致如下:

root
    src
        index.js
        ...
    .babelrc
    .package.json

In my package.json, I originally tried the following:在我的 package.json 中,我最初尝试了以下操作:

  "scripts": {
    "build": "babel --out-dir dist src",
    ...
  },

But this gave an error because of the array destructuring notation I have used in my code.但是由于我在代码中使用的数组解构符号,这给出了一个错误。 I think this is because it is not picking up my .babelrc file.我认为这是因为它没有获取我的.babelrc文件。 Using使用

babel --presets=@babel/preset-env --out-dir dist src

instead fixes this problem.而是解决了这个问题。 But I would rather I didn't have to specify plugins etc. here and rely on the .babelrc file instead.但我宁愿不必在此处指定插件等,而是依赖.babelrc文件。

From reading this issue , I get the impression babel looks for a config file in src rather than root .通过阅读这个问题,我得到的印象是 babel 在src而不是root中查找配置文件。 Looking at the documentation it seems there is an option for specifying a config file, but I can't quite get it to work correctly.查看文档似乎有一个指定配置文件的选项,但我不能让它正常工作。 My attempt:我的尝试:

babel --config-file .babelrc --out-dir dist src

You can use ./node_modules/.bin/babel in place of babel .您可以使用./node_modules/.bin/babel代替babel

Worked for me this week.这周为我工作。

Check point 3 in the overview from babel-cli https://babeljs.io/docs/en/usage检查来自 babel-cli https://babeljs.io/docs/en/usage的概述中的第 3 点

  1. And running this command to compile all your code from the src directory to lib:并运行此命令将所有代码从 src 目录编译到 lib:

./node_modules/.bin/babel src --out-dir lib

You can use the npm package runner that comes with npm@5.2.0 to shorten that command by replacing ./node_modules/.bin/babel with npx babel您可以使用 npm@5.2.0 附带的 npm package runner 来缩短该命令,方法是将./node_modules/.bin/babel替换为 npx npx babel

For Babel version 7.x, it looks for project-wide configuration in the file with name like this - babel.config.{json|js|cjs|mjs} .对于 Babel 版本 7.x,它会在文件中查找项目范围的配置,名称如下 - babel.config.{json|js|cjs|mjs} Check the documentation here .此处查看文档。

In my end,最后,

npx babel src/ -d lib/ npx babel src/ -d lib/

Babel should already pick up the .babelrc file automatically. Babel 应该已经自动选择了.babelrc文件。 If you want to add that preset, you should specify如果要添加该预设,则应指定

{
  // ... more .babelrc up here
  "presets": ["@babel/preset-env"]
  // ... more .babelrc down here
}

in your .babelrc file.在你的.babelrc文件中。

But babel will automatically search for the closest .babelrc file in the directory starting at the entry file and working its way upwards (specified here at the bottom).但是 babel 会自动在目录中搜索最近的.babelrc文件,从入口文件开始并向上工作(底部指定)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM