所以我是这个领域的新手,问题是我正在尝试编译一个带有 graphql 文件(带有 .graphql
扩展名)的 Typescript 项目。
它基于无服务器框架,因此为了编译它,我启动了 npm start
,它在命令行中启动了一个 cd src/app && tsc
。
.ts
文件像这样引用 .graphql
文件:
从“./schemaDefinition.graphql”导入 SchemaDefinition;
错误是
data/schema/index.ts(2,30): error TS2307: Cannot find module './schemaDefinition.graphql'.
我认为这里的问题出在 tsc
编译中,因为它创建了输出目录 (../../built) 但它没有复制 .graphql
文件。这是我的 tsconfig.json
文件:
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"lib": ["dom", "es6"],
"module": "commonjs",
"allowJs": true,
"moduleResolution": "node",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"rootDir": "./",
"outDir": "../../built",
"sourceMap": true,
"pretty": true,
"typeRoots": [
"node_modules/@types"
],
"types": [
"@types/node",
"@types/graphql"
],
"allowSyntheticDefaultImports": true
},
"include": [
"./*"
],
"exclude": [
"node_modules"
]
}
我不确定我是否需要做一些技巧来复制这些文件或放置一个预编译器步骤来将 .graphql
文件转换为 .ts
文件,使用像这样:GraphQL Code Generator
有什么想法吗?我卡住了:S
最佳答案
如果你在 NodeJS 中打包 banckend,它应该在 webpack.config.js
文件和 typings.d.ts
文件中配置,所以两者编辑器和打包器知道这些文件。
typings.d.ts
:
declare module "*.graphql" {
const value: any;
export default value;
}
代码:
import * as query from query.graphql
要实现这一点,使用 Webpack 的加载器(例如 raw-loader)将起作用。
module: {
rules: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.graphql$/, loader: 'raw-loader' },
]
此示例取自 https://github.com/apollographql/graphql-tools/issues/273对不同方法进行积极讨论的地方。
这是一个 GitHub 存储库,其功能大致相同但具有更强大的解决方案:https://github.com/webpack-contrib/copy-webpack-plugin
另一方面,如果您要打包前端,有一个方便的插件可以为您完成这项工作:https://www.npmjs.com/package/webpack-graphql-loader
关于node.js - 使用 graphql 文件编译 Typescript 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43818401/