【问题标题】:Firebase hosting throws error: Uncaught SyntaxError: Unexpected identifierFirebase 托管引发错误:Uncaught SyntaxError: Unexpected identifier
【发布时间】:2018-05-15 11:36:32
【问题描述】:

我正在尝试使用 firebase-hosting 托管一个网站,但出现错误: Uncaught SyntaxError: Unexpected identifier

它发生在script.js:1。源代码如下所示:

import axios from 'axios';

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!');
    } catch (e) {
        console.log(e);
    }
    console.log(res);
}

我的文件夹结构如下(关注公共树):

我正在调用index.html中的脚本:

<head>
  <title>Fantastic title</title>
  <script src="script.js"></script>
</head>

我的firebase-functions 导入工作正常,但我有一个package.json 文件,我认为这是我遇到问题的原因之一?

我的firebase.json 文件如下所示:

{
  "database": {
    "rules": "database.rules.json"
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ],
    "source": "functions"
  },
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

【问题讨论】:

    标签: firebase google-cloud-functions importerror firebase-hosting


    【解决方案1】:

    错误来自包含代码的行1

    import axios from 'axios';
    

    这是ES Module import 声明。浏览器中的本机模块支持仍然很新。 Firefox 刚刚开始发布这个May 9, 2018。您需要确保您使用的是supports modules 的浏览器。

    当你加载一个模块脚本时你需要tell the browser

    <script type="module" src="script.js"></script>
    

    另一个问题是from'axios'。浏览器不知道 npm 包和包名,所以你必须指定一个位置。

    import * as axios from '/node_modules/axios/dist/axios.min.js';
    

    import * as axios from 'https://unpkg.com/axios@0.18.0/dist/axios.min.js';
    

    packageName 中的import 是一种速记工具,用于引用本地安装的依赖项。

    由于您在脚本中运行import,因此它被视为dynamic import。动态导入目前仅在 Chrome 中提供,并且具有不同的语法。

    import('https://unpkg.com/axios@0.18.0/dist/axios.min.js')
      .then(axios => {
        axios.get(...);
      });
    

    最终,您正在尝试使用尚未完全准备好使用的技术。我建议考虑添加类似 WebpackGulp 的构建步骤。

    【讨论】:

    • 感谢您的广泛回复,非常有帮助!我有一个关于 firebase 的后续问题,因为它们只支持静态内容,这也会起作用吗?
    • 您实际上可以为Functions through Hosting 服务。如果您在 TypeScript 中编写函数,则可以在 Functions 中使用原始导入,但无法将 JS 文件提供给用户。
    猜你喜欢
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多