I’m trying to use the Google Translate API in my website.
I imported the ‘google-cloud/translate’ npm package and added the following sample code that Google provided.
const { TranslationServiceClient } = require ( ‘@google-cloud/translate’ );
const translationClient = new TranslationServiceClient ();
const projectId = ‘MYPROJECTID’ ;
const location = ‘global’ ;
const text = ‘Hello, world!’ ;
async function translateText ( ) {
const request = {
parent : projects/ ${ projectId } /locations/ ${ location }
,
contents : [ text ],
mimeType : ‘text/plain’ , // mime types: text/plain, text/html
sourceLanguageCode : ‘en’ ,
targetLanguageCode : ‘es’ ,
};
const [ response ] = await translationClient . translateText ( request );
**for** ( **const** translation **of** response . translations ) {
console . log ( `Translation: ${ translation . translatedText }`);
}
}
$w . onReady ( function ()
{
console . log ( “OK” );
translateText ();
});
When I preview the page, the code doesn’t execute, not even the console.log(“OK”); line. I noticed that if I comment out the ‘require’ line, the code executes (with no translation occurring of course). So I figure it’s the call to the npm package that’s somehow generating an error.
Ideas?