如何让Vue(vue cli 3)正确处理GraphQL文件?

11

我有一个基于vue-cli 3的新项目,在src/文件夹中有.graphql文件,例如:

#import "./track-list-fragment.graphql"

query ListTracks(
  $sortBy: String
  $order: String
  $limit: Int
  $nextToken: String
) {
  listTracks(
    sortBy: $sortBy
    order: $order
    limit: $limit
    nextToken: $nextToken
  ) {
    items {
      ...TrackListDetails
    }
    nextToken
  }
}

当我运行yarn serve时,它抱怨没有GraphQL的加载程序:

Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
> #import "./track-list-fragment.graphql"
|
| query ListTracks(

但我确实已经正确设置了我的vue.config.js(我想是这样的):

const webpack = require('webpack');
const path = require('path');

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        $scss: path.resolve('src/assets/styles'),
      },
    },
    plugins: [
      new webpack.LoaderOptionsPlugin({
        test: /\.graphql$/,
        loader: 'graphql-tag/loader',
      }),
    ],
  },
};

我该如何解决这个问题?

2个回答

4

这个可以用!

const path = require('path');

module.exports = {
  pluginOptions: {
    i18n: {
      locale: 'en',
      fallbackLocale: 'en',
      localeDir: 'locales',
      enableInSFC: false,
    },
  },
  configureWebpack: {
    resolve: {
      alias: {
        $element: path.resolve(
          'node_modules/element-ui/packages/theme-chalk/src/main.scss'
        ),
      },
    },
  },
  chainWebpack: config => {
    config.module
      .rule('graphql')
      .test(/\.graphql$/)
      .use('graphql-tag/loader')
      .loader('graphql-tag/loader')
      .end();
  },
};

4
我相信 LoaderOptionsPlugin 不是你想要的。webpack文档提到这是用于从webpack 1迁移到webpack 2的。但这不是我们在这里要做的。
配置loader的方式在 "正常的" webpack 配置文件 中如下:
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          }
        ]
      }
    ]
  }
};

按照这种方法,并假设我正确理解了Vue 3文档,以下是我如何使用原始示例数据配置Vue 3应用程序的方式:

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            { loader: 'style-loader' },
            {
              loader: 'css-loader',
              options: {
                modules: true
              }
            }
          ]
        }
      ]
    }
  }
}

现在,我们需要配置graphql加载器而不是css加载器:
module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.graphql$/,
          use: 'graphql-tag/loader'
        }
      ]
    }
  }
}

这是未经测试的,我只是根据自己对webpack和Vue文档的理解进行操作。我没有项目来测试它,但如果您提供项目链接,我将非常乐意测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接