【问题标题】:Confuse: how to use es6 browser module withTypescript (without module bundler)混淆:如何使用 es6 浏览器模块与 Typescript(没有模块捆绑器)
【发布时间】:2018-10-24 07:47:37
【问题描述】:

我想用 es6 模块组织我的打字稿代码,并通过脚本 type="module" 直接在浏览器中加载它们。我已经检查了支持 (https://caniuse.com/#feat=es6-module),它会起作用。我使用的是 chrome 版本 66。

我尝试过但没有成功(参见下面的代码),而且我对使用正确的策略感到困惑。

解决方案1:在app.ts文件中,我应该导入外部模块,然后如何加载正确的js文件?

解决方案2:在app.ts文件中,我应该直接导入.js代码,但是如何引用.d.ts文件进行类型检查?

任何帮助将不胜感激。

================================================ =========================

这是我尝试过的代码

我的 index.html 文件

<!-- index.html -->
<!DOCTYPE html>
<html>

<head>
  <title>Welcome</title>
</head>

<body>
  <div id="app">
    <img src="https://vuejs.org/images/logo.png" alt="Vue logo">
    <h1>{{ msg }}</h1>
  </div>

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

</html>

我的 app.ts 文件

//Solution 1
// import Vue from "vue"; // Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".

//Solution 2
import Vue from "./Vendors/vue.esm.browser.js"; // It works in the browser but i have lost the definition inside Typescript file

var app = new Vue({
    el: '#app',
    data: {
        msg: 'hello :)!'
    }
});

我的 tsconfig.json 文件

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "allowJs": true
  }
}

我的 package.json 文件

{
  "name": "vuejsbrowseresmodule",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "vue": "^2.5.16"
  }
}

【问题讨论】:

  • 如果你想对 VueJS 进行严格的类型检查,看看 vue-property-decorator :)

标签: typescript vuejs2 es6-modules


【解决方案1】:

经过几天的研究,我找到了答案。 目前,不使用模块加载器就无法使用 typescript。 有很多关于打字稿中浏览器中的本机加载器的讨论​​。

更多信息在这里=>

https://github.com/Microsoft/TypeScript/issues/16577 https://github.com/Microsoft/TypeScript/issues/13422

一个有趣的提案草案已经开始,可以在这里找到 =>

https://github.com/domenic/package-name-maps

【讨论】:

    【解决方案2】:

    我可能已经找到了解决办法。

    创建一个声明文件,比如 vue.d.ts

    在里面写

    declare var vue: typeof import("vue/index")
    

    然后在你的 ts 代码中,你有 global var vue 提供正确的类型 由于该文件不会出现在浏览器中,因此浏览器中的 js 代码将使用您的 cdn vue.js 文件中的全局 vue

    免责声明:我没有尝试过vue,它适用于@type/bootstrap

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 2018-11-11
      • 1970-01-01
      • 2018-07-07
      相关资源
      最近更新 更多