![](/img/trans.png)
[英]Installing Plaiceholder in Next.js / Webpack 5 causes: Module not found: Can't resolve 'child_process'
[英]I'm Trying to Inject An NPM package As A Plugin on A Next.js App to Avoid A "Module not found: Can't resolve 'child_process'" Error
我有開發 nuxt 應用程序的經驗,但我是 next.js 應用程序的新手。 在我嘗試制作的 next.js 應用程序中,我無法讓“google-auth-library”在component
中工作。 這是我的相關component
代碼:
組件/Middle.tsx
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() 中的代碼適用於常規節點應用程序。 我制作了一個節點應用程序,我將 function 放在一個index.js
文件中並使用node index.js
運行它並且運行完美。 問題是當我用yarn dev
運行這個應用程序時,我得到一個空白的瀏覽器頁面,並且在我的終端中是這樣的:
<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 應用程序,我遇到了類似的問題,其中有一個名為“unity-webgl”的 package。 我通過plugins
文件夾將其注入應用程序來解決問題。 我做了這個文件:
插件/插件-unity-webgl.client.js
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 中聲明它
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 文件有很大不同:
下一步.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
您可以注入插件讓它們僅使用 next.js 應用程序運行客戶端嗎? 我該怎么做?
更新:
這是我的 Github 代碼回購協議。 本題重點是components/Middle.ts https://github.com/ChristianOConnor/call-to-cloud-exp
他們的關鍵是您必須將GoogleAuth
api 調用放在pages/api
路由中。 這是一個如何調用 Google Cloud Function 的示例。順便說一句,我使用命令npx create-next-app@latest call-to-cloud-exp --typescript
為該示例制作了基本模板
頁面/api/google.ts
// 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 })
}
組件/Middle.tsx
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
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
嘗試動態導入 package。 這可能是因為 nextjs SSR。 在您使用此 npm package 的任何地方動態調用您的組件,如下面的文檔所示。
const DynamicComponent = dynamic(() => import('../components/hello'))
參考文檔:- https://nextjs.org/docs/advanced-features/dynamic-import
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.