【问题标题】:How to import jQuery npm module in TypeScript 1.8如何在 TypeScript 1.8 中导入 jQuery npm 模块
【发布时间】:2016-07-22 02:22:01
【问题描述】:

首先,我很难问出正确的问题。我觉得我错过或混淆了关于 TypeScript 编译器、新 ES2015 (ES6) 模块语法和模块加载器的一些概念。

我正在尝试使用 ES2015 模块语法导入 npm 安装的 jquery 模块。 Typescript 应该将其转换为 ES5。

打开 index.html 时出现错误。

system-polyfills.src.js:1276 Error: SyntaxError: Unexpected token <
Evaluating http://localhost:3000/jquery
Error loading http://localhost:3000/app/main.js

index.html

<html>
  <head>
    <title>Bare TypeScript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/jquery/dist/jquery.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <div>Loading...</div>
  </body>
</html>
  • 我不确定<script src="node_modules/jquery/dist/jquery.js"></script> 是否必要。
  • console.log($) 被评论时,B 导入怎么能正常工作 出去? jQuery导入也应该工作?
  • 也许将 npm 的 commonjs 模块与 systemjs 混合是问题?

main.ts

import * as $ from 'jquery'
import B from './app.b'

console.log("Monkey");
let b = new B();
console.log($);

如何配置 tsc 以使用 ES2015 模块语法? 使用 TypeScript 1.8。

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

package.json

"dependencies": {
    "es6-shim": "^0.35.0",
    "jquery": "^2.2.2",
    "systemjs": "0.19.25"
  },

typings.json

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jquery": "registry:dt/jquery#1.10.0+20160316155526"
  }
}

【问题讨论】:

    标签: typescript npm ecmascript-6


    【解决方案1】:

    您正在尝试将 jQuery 作为 systemjs 模块加载,但它是 AMD。 此外,除非您在 app.b 上有默认导出,否则 typescript 编译器会抛出错误。您是否检查过是否遇到任何编译器错误?

    Github 对使用 ES6 导入语法加载 jQuery 有一些见解。

    【讨论】:

    • 我没有收到编译器错误。当注释掉console.log($) "monkey" 时,文本会被写入控制台。感谢 GitHub 链接。
    猜你喜欢
    • 2018-08-25
    • 2020-06-13
    • 2020-06-27
    • 2018-11-01
    • 2013-04-12
    • 1970-01-01
    • 2020-05-29
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多