代码之家  ›  专栏  ›  技术社区  ›  rdhainaut

混淆:如何使用带有TypeScript的es6浏览器模块(没有模块绑定器)

  •  4
  • rdhainaut  · 技术社区  · 8 年前

    我想用es6模块组织我的typescript代码,并通过浏览器中的script type=“module”直接加载它们。我已经检查了支架( https://caniuse.com/#feat=es6-module )这会奏效的。我使用chrome版本66。

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

    解决方案1 :应用程序内。ts文件,我应该导入外部模块,但如何加载正确的js文件?

    解决方案2 :应用程序内。ts文件,是否应直接导入。js代码,但如何引用。d、 ts文件是否具有签入类型?

    任何帮助都将不胜感激。

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

    这是我尝试过的代码

    我的索引。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>
    

    我的应用程序。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
      }
    }
    

    我的包裹。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"
      }
    }
    
    2 回复  |  直到 8 年前
        1
  •  5
  •   rdhainaut    8 年前

    经过几天的研究,我找到了答案。 目前,如果不使用模块加载器,就不可能使用typescript。 关于typescript中浏览器中的本机加载程序,有很多讨论。

    此处提供更多信息=>

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

    一份有趣的提案草案已经开始,并可在此处找到=>

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

        2
  •  0
  •   Dharman vijay    4 年前

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

    创建声明文件,例如vue。d、 ts

    在其中写入

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

    然后在ts代码中,有全局变量 vue 提供正确的类型 由于此文件不会显示在浏览器中,因此浏览器中的js代码将使用全局 vue 从您的cdn vue。js文件。

    免责声明:我没有尝试过 vue ,它与 @type/bootstrap 。