简体   繁体   English

如何在React将使用的npm包中使用babel

[英]How to use babel with npm package that will be used by react

Trying to do what I thought was a simple thing. 尝试做我认为很简单的事情。

I have a node package that uses advanced js syntax. 我有一个使用高级js语法的节点包。 I want to depend on it in a react project. 我想在React项目中依靠它。

So I installed babel packages via --save-dev , and added a .babelrc : 所以我通过--save-dev安装了babel软件包,并添加了.babelrc

{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}

That was not enough so I added an npm script under install to trigger the compilation. 那还不够,所以我在install下添加了一个npm脚本来触发编译。 Then I had to include the compiled target lib/index.js as my entry point via main . 然后,我必须通过main将编译后的目标lib/index.js为我的入口点。 So in the end my package.json looks something like this: 所以最后我的package.json看起来像这样:

{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },  
  "main": "lib/index.js",
  "dependencies": {},  
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}

When I run npm install locally on this project, it builds properly. 当我在此项目上本地运行npm install ,它会正确构建。 However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found . 但是,当react脚本构建此脚本时(dep来自github),我得到一个错误: sh: 1: babel: not found

Why is this so difficult? 为什么这么难? What am I doing wrong? 我究竟做错了什么?

sh: 1: babel: not found is from your shell not finding the babel binary file (normally under ./node_modules/.bin/babel) sh: 1: babel: not found是从您的shell中找不到babel二进制文件(通常在./node_modules/.bin/babel下)

You'd want to compile before you publish to npm, so anyone who installs your package has the built files. 在发布到npm之前,您需要进行编译,因此安装软件包的任何人都具有内置文件。 But, for Github try something like: 但是,对于Github,请尝试以下操作:

"postinstall": "npx babel src --out-dir lib"

This hack worked instead of the postinstall : 这个hack代替了postinstall

...
"preinstall": "npm install --ignore-scripts && babel src --out-dir lib",
...

Source: https://github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098 来源: https : //github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098

Also relevant: https://github.com/npm/npm/issues/10366 也相关: https : //github.com/npm/npm/issues/10366

I am not sure I understand the need here correctly, but could you not just run the babel call in prepare or prepublish scripts? 我不确定我是否正确理解了这里的需求,但是您能否仅在prepareprepublish脚本中运行babel调用? That way only local npm install calls would pick that up. 这样,只有本地npm install调用才能接听。

See more about npm scripts lifecycle: https://docs.npmjs.com/misc/scripts 查看有关npm脚本生命周期的更多信息: https ://docs.npmjs.com/misc/scripts

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

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