首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我试图在Next.js应用程序上插入一个NPM包作为插件,以避免“模块找不到:无法解决'child_process'”错误

我试图在Next.js应用程序上插入一个NPM包作为插件,以避免“模块找不到:无法解决'child_process'”错误
EN

Stack Overflow用户
提问于 2022-04-29 20:25:03
回答 2查看 486关注 0票数 2

我有开发nuxt应用程序的经验,但我是next.js应用程序的新手。在我试图制作的next.js应用程序上,我很难让“google库”在component中工作。这是我的component代码:

组件/中间.

代码语言:javascript
复制
import React from 'react';
import { Button } from 'react-bootstrap';
import { GoogleAuth } from 'google-auth-library';

const url = "https://us-central1-gtwitone.cloudfunctions.net/<functionname>";
const keyFilename = "/path/to/my/key.json";
//const functionsClient = CloudFunctionsServiceClient.v1.CloudFunctionsServiceClient;

class Middle extends React.Component {
    async main() {
      const auth = new GoogleAuth({keyFilename: keyFilename})

      //Create your client with an Identity token.
      const client = await auth.getIdTokenClient(url);
      const res = await client.request({url});
      console.log(res.data);
  }

    render() {
      return (
        <div className="col-md-12 text-center">
            <Button variant='primary' onClick={this.main}>
                Click me
            </Button>
        </div>
      );
    }
  }

export default Middle;

我知道main()中的代码在常规节点应用程序中工作。我制作了一个节点应用程序,我把这个函数放在一个index.js文件中,用node index.js运行它,它运行得很完美。问题是,当我使用yarn dev运行这个应用程序时,我会得到一个空白的浏览器页面,这个页面在我的终端中:

代码语言:javascript
复制
<myusername>@<mycomputername> <myappname> % yarn dev
yarn run v1.22.17
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
wait  - compiling...
event - compiled client and server successfully in 214 ms (124 modules)
wait  - compiling / (client and server)...
wait  - compiling...
error - ./node_modules/google-auth-library/build/src/auth/googleauth.js:17:0
Module not found: Can't resolve 'child_process'

Import trace for requested module:
./node_modules/google-auth-library/build/src/index.js
./components/Middle.tsx
./pages/index.tsx

https://nextjs.org/docs/messages/module-not-found
Native Node.js APIs are not supported in the Edge Runtime. Found `child_process` imported.

Could not find files for / in .next/build-manifest.json
Could not find files for / in .next/build-manifest.json
^C
<myusername>@<mycomputername> <myappname> % 

我认为这个错误是由于服务器端呈现的问题造成的。我写了一个nuxt应用程序,其中我有一个类似的问题,与一个包名为‘团结-webgl’。我通过一个plugins文件夹将它注入应用程序,从而解决了这个问题。我做了这个文件:

插件/插件-统一-webgl.client.js

代码语言:javascript
复制
import UnityWebgl from "unity-webgl";

export default ({ _ }, inject) => {
  const Unity = new UnityWebgl({
    loaderUrl: "/Build/tetris.loader.js",
    dataUrl: "/Build/tetris.data",
    frameworkUrl: "/Build/tetris.framework.js",
    codeUrl: "/Build/tetris.wasm",
  });
  inject("webgl", Unity);
};

我还需要在nuxt.config.js中声明这一点

代码语言:javascript
复制
import colors from 'vuetify/es5/util/colors'

export default {
  // Set server port
  server: {
    port: 8080
  },
  /*
  ** Nuxt rendering mode
  ** See https://nuxtjs.org/api/configuration-mode
  */
  mode: 'universal',

  // Target: https://go.nuxtjs.dev/config-target
  target: 'static',

  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    titleTemplate: '%s - appFrontend',
    title: 'appFrontend',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    '~/plugins/persistState.js',
    '~/plugins/axios.js',
    '~/plugins/plug-unity-webgl.client.js'
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/vuetify
    '@nuxtjs/vuetify'
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios'
  ],

  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {
    // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308
    browserBaseURL: process.env.API_URL
  },

  // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: true,
      themes: {
        dark: {
          primary: colors.blue.darken2,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3
        }
      }
    }
  },

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
  }
}

注意plugins数组。那么,我将如何对我正在开发的这个next.js应用程序做一些类似的事情呢?next.config.js文件看起来与nuxt.config.js文件非常不同:

next.config.js

代码语言:javascript
复制
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
}

module.exports = nextConfig

你能注入插件让他们只运行客户端的next.js应用程序吗?我该怎么做?

更新:

这是我对代码的回复。这个问题的焦点是组件/medile.ts https://github.com/ChristianOConnor/call-to-cloud-exp

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-01 23:18:57

它们的关键是您必须将GoogleAuth api调用放在pages/api路由中。这是一个如何调用Google函数的例子。顺便说一句,我使用命令npx create-next-app@latest call-to-cloud-exp --typescript为示例创建了基本模板

pages/api/google.ts

代码语言:javascript
复制
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next"
import { GoogleAuth } from "google-auth-library"

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    const url = process.env.FUNCTION_URL as string

    //Example with the key file, not recommended on GCP environment.
    const auth = new GoogleAuth({ keyFilename: process.env.KEYSTORE_PATH })

    //Create your client with an Identity token.
    const client = await auth.getIdTokenClient(url)
    const result = await client.request({ url })
    console.log(result.data)
    res.json({ data: result.data })
}

组件/中间.

代码语言:javascript
复制
import React from "react"
import { Button } from "react-bootstrap"

class Middle extends React.Component {
  handleClick() {
        console.log("this is:", this)
    }
  
  // this talks with /pages/api/google
  async imCallingAnAPI() {
    const result = await fetch("/api/google")
    console.log({ result })
  }

  render() {
    return (
      <div className="col-md-12 text-center">
        <Button variant="primary" onClick={this.imCallingAnAPI}>
          Click me
        </Button>
      </div>
    )
  }
}

export default Middle

页/index.tsx

代码语言:javascript
复制
import type { NextPage } from 'next'
import Header from '../components/Header';
import Footer from '../components/Footer';
import Middle from '../components/Middle';

const Home: NextPage = () => {
  return (
    <><main className='d-flex flex-column min-vh-100'>
      <Header />
      <br></br>
      <br></br>
      <Middle />
      </main>
      <footer>
        <Footer />
      </footer>
    </>
  )
}

export default Home
票数 2
EN

Stack Overflow用户

发布于 2022-04-29 21:29:12

尝试动态导入包。这可能是因为nextjs SSR。在使用此npm包的地方动态调用组件,如下面的文档所示。

DynamicComponent = =>导入(‘./=>/hello’))

参考文档:- https://nextjs.org/docs/advanced-features/dynamic-import

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72063340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档