babel-node vs node:带有导入/导出的graphql文件

Posted

技术标签:

【中文标题】babel-node vs node:带有导入/导出的graphql文件【英文标题】:babel-node vs node: graphql files with import/exports 【发布时间】:2018-05-01 19:42:28 【问题描述】:

NodeJS 似乎不理解 graphql 文件(扩展名 .gql)中的导入/导出命令,但 babel-node 可以。我能想到的唯一解决方法是将 .gql 文件重命名为 .js 文件,但我失去了语法突出显示。

是否有一个简单的修复方法可以在非 js 扩展的文件中引入节点荣誉导入/导出?附上我的package.json; npm run dev 有效,但 npm run build; npm run start 无效:


"name": "MyAPI",
"version": "1.0.0",
"description": "MyAPI using GraphQL",
"main": "api/server.js",
"scripts": 
    "build": "babel api -d src --copy-files",
    "start": "node src/server.js",
    "debug": "babel-node --inspect api/server.js",
    "dev": "nodemon api/server.js --watch api --watch tests --ext js,gql --exec babel-node",
    "lint": "eslint api,tests",
    "test": "mocha --require babel-core/register tests"
,
"author": "JML",
"devDependencies": 
    "apollo-client": "^2.0.2",
    "apollo-client-preset": "^1.0.2",
    "babel-eslint": "^7.2.1",
    "babel-plugin-syntax-object-rest-spread": "^6.13.0",
    "babel-plugin-transform-async-generator-functions": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.0",
    "babel-preset-stage-3": "^6.24.1",
    "chai": "^4.1.2",
    "chai-subset": "^1.6.0",
    "eslint": "^4.3.0",
    "eslint-plugin-babel": "^4.1.2",
    "graphql": "^0.10.5",
    "mocha": "^4.0.1",
    "node-fetch": "^1.7.3",
    "nodemon": "^1.11.0",
    "randexp": "^0.4.6"
,
"dependencies": 
    "babel-cli": "^6.24.0",
    "babel-core": "^6.25.0",
    "babel-preset-latest": "^6.24.1",
    "babel-runtime": "^6.26.0",
    "body-parser": "^1.17.1",
    "casual": "^1.5.14",
    "cors": "^2.8.4",
    "eslint": "^4.10.0",
    "express": "^4.15.2",
    "graphql-server-express": "1.0.4",
    "graphql-tag": "^2.5.0",
    "graphql-tools": "^1.1.0",
    "lodash": "^4.17.4",
    "mysql": "^2.14.1",
    "nano": "^6.4.2",
    "treeize": "^2.1.2"

【问题讨论】:

【参考方案1】:
npm install babel-cli babel-preset-env

一旦你安装了这些,它将在根级别创建填充的 .babelrc 文件。你不需要修改。那么你需要将这些配置加载到 package.json 中的启动脚本中。

"start": "nodemon src/index.js --ext js,graphql --exec babel-node  ",

如果你不知道nodemon,你需要全局安装它,它会监视src/index.js 文件。

--ext js, graphql // 这是可选的。它将有 vscode 来为代码着色。

最后,你需要配置 babel 来支持对象扩展操作符。

npm install babel-plugin-transform-object-rest-spread

然后将这个“transform-object-rest-spread”添加到 .babelrc 文件中的 plugins 数组中。

.babelrc


  "presets": ["env", "react", "stage-0"],
  "plugins": [
    "transform-class-properties",
    "transform-decorators",
    "transform-react-constant-elements",
    "transform-react-inline-elements",
    "transform-object-rest-spread"
  ]

【讨论】:

以上是关于babel-node vs node:带有导入/导出的graphql文件的主要内容,如果未能解决你的问题,请参考以下文章

babel-node 无法在 node_modules 中需要 jsx 文件

package.json 启动脚本,babel-node:在 heroku deploy 上找不到

项目中安装babel-node

[NODEMON]- babel-node 未被识别为内部或外部命令

如何使用“babel-node --presets es2015,stage-3”为电子应用程序设置 npm start

babel-node + Express NodeJS项目搭建指南