Firebase Hosting部署报错:Uncaught SyntaxError: Unexpected identifier
Let's break down why you're hitting this error and walk through the fixes step by step:
1. The Immediate Syntax Error: ES Modules in Browser Scripts
Your script.js uses ES Module syntax (import axios from 'axios';), but your HTML script tag doesn't tell the browser to treat it as a module. Browsers default to parsing scripts as traditional non-module code, so the import keyword throws an "Unexpected identifier" error right on line 1.
Fix the script tag in index.html:
<head> <title>Fantastic title</title> <!-- Add type="module" to enable ES Module support --> <script type="module" src="script.js"></script> </head>
2. Missing Axios in the Public Directory
You’re correct to suspect the missing package.json in public—without it, axios isn’t present in your deployed files, so even if you fix the module issue, the browser won’t know where to find axios. You have two simple options here:
Option A: Use a CDN for Axios
Skip local installation and import directly from a CDN in script.js:
// Replace the import line with this CDN-based import import axios from 'https://cdn.jsdelivr.net/npm/axios@1.6.0/+esm'; callWs(); console.log('This worked now!'); async function callWs() { try { const res = await axios( `https://us-central1-jpabiggmbh-001.cloudfunctions.net/realexData?amt=${500}&curr=${'CHF'}` ); console.log('This function ran just now!'); console.log(res); // Move this inside the try block where res is defined } catch (e) { console.log(e); } }
Option B: Bundle Your Code with a Tool (like Vite)
If you prefer using local dependencies:
- Initialize
package.jsonin your project root:npm init -y npm install axios - Install Vite for bundling:
npm install -D vite - Create a
vite.config.jsto point to your script:import { defineConfig } from 'vite'; export default defineConfig({ build: { outDir: 'public/dist', rollupOptions: { input: './public/script.js', }, }, }); - Build the bundled file:
npx vite build - Update your HTML to use the bundled script:
<script src="dist/script.js"></script>
3. Fix the res Variable Scope Issue
In your original code, console.log(res); sits outside the try block where res is declared. This will throw a "res is not defined" error once you fix the initial syntax issue. Move that line inside the try block where res is in scope (as shown in the CDN example above).
4. Double-Check Firebase Hosting Configuration
Your firebase.json looks correct for hosting the public directory, but confirm:
- Bundled files (like
dist/script.js) aren’t excluded by yourignorerules (your current setup only skipsnode_modulesand hidden files, so bundled assets will deploy fine). - Redeploy your changes with
firebase deploy --only hostingto push updates to Firebase.
Once you implement these fixes, the syntax error should be resolved, and your function should call the Firebase Cloud Function as expected.
内容的提问来源于stack exchange,提问作者Spurious

