javascript - 未捕获的语法错误 : Unexpected identifier - importing jquery

标签 javascript jquery node.js typescript

我的网站项目中的导入语句有问题。尝试使用nodejs - typescript 和 jquery

我的项目文件夹如下所示:

  • 项目
    • Node 模块
    • 公开
      • js
      • jquery/dist(复制node_modules/jquery/dist)
      • index.html
    • ts
      • 测试.ts
  • package.json
  • tsconfig.json

package.json:

{
  "name": "testclient",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/jquery": "^3.3.4",
    "jquery": "^3.3.1"
  },
  "devDependencies": {
    "typescript": "^2.9.2"
  }
}

tsconfig.json:

{
    "compileOnSave": true,
    "compilerOptions": {
        "experimentalDecorators": true,
        "sourceMap": true,
        "strict": true,
        "module": "ES2015",
        "moduleResolution": "Classic",
        "target": "ES5",
        "lib": ["dom", "es5", "es2015", "es2015.promise"],
        "removeComments": true,
        "sourceMap": true,
        "outDir": "public/js",
        "allowSyntheticDefaultImports": true
    },
    "include": [
        "ts/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

index.html

<!DOCTYPE html>
<html lang="de">
    <header>
        <title>Test</title>
    </header>
    <body>
        Mein Test
    </body>
    <script type="text/javascript" src="js/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="js/test.js"></script>
</html>

测试.ts

import $  from 'jquery';
$(document).ready(() => {
    console.log('document is ready now');
    console.log($);
});

如果我在 Chrome 浏览器中启动 index.html 并打开控制台,我会收到错误:

Uncaught SyntaxError: Unexpected identifier test.js:1

我发现 $ 目前还不知道,我将其称为 jquery。所以我不能在我的脚本中使用 jquery

在不使用 ///<reference path=""/> 的情况下运行它的最佳实践是什么?用于导入 jquery.要设置哪些 tsconfig 参数才能使其在浏览器中运行?

最佳答案

不确定我是否完全理解这个问题(它的表述有点奇怪),但我认为您正在尝试在索引页中实现 jquery,而无需下载和映射它,您可以通过在代码中实现它来简单地做到这一点:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您还收到错误,因为您的 test.js 路径错误,它应该是

<script type="text/javascript" src="../ts/test.js"></script>

如果我考虑你的映射

关于javascript - 未捕获的语法错误 : Unexpected identifier - importing jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059553/

相关文章:

javascript - vue cli - 未捕获的语法错误 : Unexpected token <

javascript - 无法隐藏文件附件浏览按钮

javascript - 从选择中重置/取消绑定(bind)更改事件

javascript - 如果选项卡内容为空,则无法隐藏导航选项卡

javascript - 在nodejs中从集合/列表生成有序对

javascript - 调用函数时返回 jquery.deferred 对象的响应

javascript - 如何在数组中更深一层

javascript - 如何在 JavaScript 中向现有变量添加变量?

node.js - Nodejs异步提取zip

node.js - 在 azure 上部署应用程序期间,Visual Studio 总是卡住