【问题标题】:Typescript equivalent of inline JavaScript相当于内联 JavaScript 的打字稿
【发布时间】:2019-09-28 19:50:13
【问题描述】:

这可能是不言而喻的,但我没有找到任何可以说明我正在尝试做什么的示例(也许我只是做错了)。我正在将 Vue 添加到现有的 ASP.NET Core MVC 应用程序并将 JavaScript 语句直接添加到页面中,但是当我尝试迁移到 TypeScript 文件时没有任何反应。

JavaScript 是:

new Vue({
    el: "#productPage",
      data: {
        isLoading: true
    },
    methods: {
    },
    mounted () {
        console.log("mounted()");
        this.isLoading = false;
    }
});

这按预期工作。将代码迁移到 TypeScript 文件 productPage.ts:

import Vue from 'vue';

new Vue({
  el: "#productPage",
  data: {
      isLoading: true
  },
  methods: {
  },
  mounted () {
      console.log("mounted()");
      this.isLoading = false;
  }
});

生成:

(function (factory) {
  if (typeof module === "object" && typeof module.exports === "object") {
      var v = factory(require, exports);
      if (v !== undefined) module.exports = v;
  }
  else if (typeof define === "function" && define.amd) {
      define(["require", "exports", "vue"], factory);
  }
})(function (require, exports) {
  "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  var vue_1 = require("vue");
  var HonestyBox;
  (function (HonestyBox) {
      new vue_1.default({
          el: "#productPage",
          data: {
              isLoading: true
          },
          methods: {},
          mounted: function () {
              console.log("Mounted !!!!");
              this.isLoading = false;
          }
      });
  })(HonestyBox || (HonestyBox = {}));
});
//# sourceMappingURL=productPage.js.map

并包括生成的javascript文件productPage.js

<script src="~/js/productPage.js"></script>

这没有任何作用。单步执行调试器时,function(factory) 中的任何一个条件都不满足。控制台告诉我 You are running Vue in development mode. 但包含的 JavaScript 无法运行。用于生成 JavaScript 文件的tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "umd",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "es5",
    "outDir": "wwwroot/js"
  },
  "include": [
    "Typescript/**/*"    
  ],
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

使用"module": "commonjs" 会产生ReferenceError: exports is not defined。我希望避免使用 Browserify 或 Webpack。

【问题讨论】:

  • 你可能不应该添加 import 语句,除非你添加了像 Webpack 这样的打包器
  • 请显示生成的productPage.js文件
  • 添加了生成的javascript。我希望避免添加捆绑器 - 有什么方法可以在不使用 import 的情况下“导入”vue?

标签: asp.net-mvc typescript asp.net-core vuejs2


【解决方案1】:

如果我理解正确,您可以在 productPage.js 之前的单独脚本标签中添加 Vue。

这意味着你不能在你的 TypeScript 文件中导入 Vue,但是你需要声明 Vue,所以模块只是假设 Vue 已经被加载(在你的 TS 模块之外)。

declare const Vue; // this replaces your Vue import statement

如果您想稍后添加捆绑器,则需要删除加载 Vue 的脚本标签,并且只采用模块化方法: Vue 需要使用 import 语句导入,以便捆绑器知道他必须包含所有 Vue。 然后,您将拥有一个 JS 文件(或者如果您的捆绑器将其拆分:多个 JS 文件)。

【讨论】:

  • 感谢@Peter,这正是我想要的。
猜你喜欢
  • 2016-01-19
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2019-10-31
相关资源
最近更新 更多