【发布时间】:2019-08-09 11:07:33
【问题描述】:
问题是如何在将 TS 编译为 JS 时自动从 JavaScript 文件中删除导入指令,或者告诉我如何在 Visual Studio 2019 中使用从 npm 下载的包来组织工作的解决方案。
我在 Visual Studio 2019 中使用 ASP.NET Core 和 MSBuild 开发 Web 应用程序,用于将 TS 编译为 JS。我创建一个 TypeScript 文件,将两个 npm 包导入其中:jQuery 和 Axios,然后将 TS 编译为 JS,并通过 Gulp 任务管理器,将库从 node_modules 文件夹复制到 wwwroot 文件夹。
最后,我有四个文件: htmldom.ts(包含使用 jQuery 和 Axios 的代码的 TypeScript 源代码);编译htmldom.js;和来自 npm 存储库的库(jquery.js 和 axios.js) 这是 TS 文件的样子:
import "../node_modules/jquery/dist/jquery.js";
import "../node_modules/@types/jquery/index";
import axios from "../node_modules/axios/index"
document.addEventListener("DOMContentLoaded", function () {
const button = document.getElementById('button');
button.addEventListener('click', function () {
$("#button").on("click", function () {
alert("hello jquery!!!");
});
var url = "https://jsonplaceholder.typicode.com/todos";
var data = axios.get(url).then(function (responce) {
console.log(responce.data);
});
console.log(data);
});
});
编译后的 JS 文件如下所示:
import "../node_modules/jquery/dist/jquery.js";
import "../node_modules/@types/jquery/index";
import axios from "../node_modules/axios/index";
document.addEventListener("DOMContentLoaded", function () {
const button = document.getElementById('button');
button.addEventListener('click', function () {
$("#button").on("click", function () {
alert("hello jquery!!!");
});
var url = "https://jsonplaceholder.typicode.com/todos";
var data = axios.get(url).then(function (responce) {
console.log(responce.data);
});
console.log(data);
});
});
//# sourceMappingURL=htmldom.js.map
这就是 MVC 视图在库中的样子:
<input type="button" id="button" value="click me" />
@section Scripts
{
<script src="~/javascripts/jquery.js" asp-append-version="true"></script>
<script src="~/javascripts/axios.js" asp-append-version="true"></script>
<script src="~/compiled/htmldom.js" asp-append-version="true"></script>
}
当我将编译好的带有库的 JS 文件放入视图时,JS 不起作用并给出错误:SyntaxError: Unexpected string
当我从 JS 文件中删除导入指令时,一切正常:
//import "../node_modules/jquery/dist/jquery.js";
//import "../node_modules/@types/jquery/index";
//import axios from "../node_modules/axios/index";
document.addEventListener("DOMContentLoaded", function () {
const button = document.getElementById('button');
button.addEventListener('click', function () {
$("#button").on("click", function () {
alert("hello jquery!!!");
});
var url = "https://jsonplaceholder.typicode.com/todos";
var data = axios.get(url).then(function (responce) {
console.log(responce.data);
});
console.log(data);
});
});
//# sourceMappingURL=htmldom.js.map
问题是如何在将 TS 编译为 JS 时自动从 JavaScript 文件中删除导入指令,或者建议我如何在 Visual Studio 2019 中使用 TypeScript 使用第三方库
【问题讨论】:
标签: javascript typescript asp.net-core visual-studio-2019