【发布时间】:2021-11-21 09:02:13
【问题描述】:
上下文
- 我的 Web 应用程序 (ASP.NET Core) 中有一个工作版本的打字稿 Hello World
- 通过 NuGet 包
"Microsoft.TypeScript.MSBuild" Version="4.4.2"和tsconfig.json使用 typscript 编译器。 (见下文) - 我想使用 3rd 方库,并通过 packages.json 成功添加
"@types/lodash": "^4.14.175"(见下文) - 我添加了
/// <reference path="../node_modules/@types/lodash/index.d.ts"/>(见下文) - 一切正常,但
/// <reference path="..."行带有绿色下划线,ESLint 显示
不要对 index.d.ts 使用三斜杠引用,而是使用 import。
好的,我稍后会使用导出/导入,所以我编辑了三斜杠参考线作为注释,并添加了import * as _ from "lodash" 行,它编译得很好,但是在 chrome 中运行时 导致运行时错误:
不能在模块外使用 import 语句
所以我将<script tag 更改为以下内容:<script type="module" src="~/js/app.js"></script>
但是这会导致以下 chrome 运行时错误:
无法解析模块说明符“lodash”。相对引用必须以“/”、“./”或“../”开头。
问题
现在我被困住了,由于我的知识非常有限,我猜想缺少一些步骤/转换,但是什么?我试图在我的 .ts 文件的导入语句中包含一些路径(导致编译错误)。编译时我想用工作中的import 指的是@typings,但是运行时lodash.js 是来自cdn,两者没有任何关系...
app.ts
// commented out / <reference path="../node_modules/@types/lodash/index.d.ts"/>
import * as _ from "lodash"
console.log(_.camelCase("Hello"));
发出的 app.js
// commented out / <reference path="../node_modules/@types/lodash/index.d.ts"/>
import * as _ from "lodash";
console.log(_.camelCase("Hello"));
//# sourceMappingURL=app.js.map
index.html
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script type="module" src="~/js/app.js"></script>
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es6",
"module": "ES6",
"outDir": "wwwroot/js"
},
"exclude": [
"node_modules",
"wwwroot"
]
}
packages.json
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"@types/lodash": "^4.14.175"
}
}
【问题讨论】:
标签: node.js typescript asp.net-core npm node-modules