如何在Angular 6应用中使用@google-cloud/speech Node.js包?
@google-cloud/speech in Angular 6 Hey there, let's break down why you're seeing those annoying compilation warnings and how to fix them.
First off, the core issue here is that @google-cloud/speech is built for Node.js server environments, not browsers. It relies on Node.js-specific core modules (like fs, path, child_process) and uses dynamic dependency imports—things Angular's default webpack setup doesn't handle out of the box for browser apps. That's where those "Critical dependency" warnings are coming from.
Option 1: (Recommended) Use a Backend Proxy
The safest and most reliable approach is to avoid using @google-cloud/speech directly in your Angular frontend. Instead, build a simple Node.js backend that handles the speech recognition, then have your Angular app call that backend's API. This keeps your Google Cloud service account keys secure (never expose them in frontend code!) and avoids all browser compatibility headaches.
Step 1: Set Up the Node.js Backend
First, create a basic Express server:
const { SpeechClient } = require('@google-cloud/speech'); const express = require('express'); const cors = require('cors'); const app = express(); // Allow CORS for your Angular app app.use(cors({ origin: 'http://localhost:4200' })); app.use(express.json({ limit: '50mb' })); // Initialize the Speech client with your service account key const speechClient = new SpeechClient({ keyFilename: './path-to-your-service-account-key.json' }); // Endpoint for speech-to-text requests app.post('/api/recognize-speech', async (req, res) => { try { const { audioContent, languageCode } = req.body; const request = { audio: { content: audioContent }, config: { encoding: 'LINEAR16', sampleRateHertz: 16000, languageCode: languageCode || 'en-US' } }; const [response] = await speechClient.recognize(request); const transcription = response.results .map(result => result.alternatives[0].transcript) .join('\n'); res.json({ success: true, transcription }); } catch (err) { console.error('Speech recognition error:', err); res.status(500).json({ success: false, error: err.message }); } }); app.listen(3000, () => { console.log('Speech recognition backend running on http://localhost:3000'); });
Step 2: Call the Backend from Angular
In your Angular component, use HttpClient to send audio data to the backend:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-speech-recognition', templateUrl: './speech-recognition.component.html', styleUrls: ['./speech-recognition.component.css'] }) export class SpeechRecognitionComponent implements OnInit { transcription: string = ''; constructor(private http: HttpClient) {} ngOnInit(): void {} async sendAudioForRecognition(audioBlob: Blob) { // Convert blob to base64 (required by the Speech API) const reader = new FileReader(); reader.onloadend = async () => { const audioContent = reader.result?.toString().split(',')[1] || ''; const response = await this.http.post('http://localhost:3000/api/recognize-speech', { audioContent, languageCode: 'en-US' }).toPromise(); this.transcription = (response as any).transcription; }; reader.readAsDataURL(audioBlob); } }
Option 2: Force @google-cloud/speech to Work in Angular (Not Recommended)
If you absolutely need to use the package directly in the frontend (note: this is risky for security and may have stability issues), you can tweak Angular's webpack config to polyfill Node.js modules and suppress warnings.
Step 1: Install Required Dependencies
npm install --save-dev @angular-builders/custom-webpack node-polyfill-webpack-plugin path-browserify
Step 2: Create a Custom Webpack Config
Make a file named webpack.extra.js in your project root:
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin'); module.exports = { plugins: [ new NodePolyfillPlugin() ], resolve: { fallback: { // Ignore Node.js modules that don't exist in browsers "fs": false, "child_process": false, "net": false, "tls": false, // Polyfill modules that have browser equivalents "path": require.resolve("path-browserify") } }, module: { rules: [ // Transpile problematic modules to ES5 { test: /\.js$/, exclude: /node_modules\/(?!@google-cloud\/speech|grpc)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ], // Suppress dynamic dependency warnings exprContextCritical: false } };
Step 3: Update Angular.json to Use Custom Webpack
In your angular.json, replace the default build and serve builders with the custom ones:
{ "projects": { "your-project-name": { "architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./webpack.extra.js" }, // ... rest of your build options } }, "serve": { "builder": "@angular-builders/custom-webpack:dev-server", "options": { "customWebpackConfig": { "path": "./webpack.extra.js" }, // ... rest of your serve options } } } } } }
Final Notes
- Security Warning: If you go with Option 2, you'll have to include your Google Cloud service account key in the frontend, which is a huge security risk—anyone can extract it and misuse your Cloud resources. Stick with Option 1 if at all possible.
- Web Speech API Alternative: For pure browser-side speech recognition without Google Cloud, check out the native Web Speech API—it's free and works directly in the browser.
内容的提问来源于stack exchange,提问作者Cedric Arnould

