![](/img/trans.png)
[英]Typescript: How do I import and add typings for a nested file in node_modules?
[英]How to import node modules in simple typescript
我是 TypeScript 的新手,我只是想包含一個從節點模塊導入的模塊。 我沒有使用 webpack 或任何其他構建工具,因為我試圖保持盡可能基本的理解。
這是我的結構:
/node_modules -- contains node modules I want to import in main.ts
/scripts/ts/main.ts
/scripts/main.js -- the transpiled main.ts file
/index.html -- includes the module script tag for scripts/main.js
/package.json
/tsconfig.json
這是我的 tsconfig.json:
{
"compilerOptions": {
"target": "ES6",
"module": "ES2015",
"strict": true,
"forceConsistentCasingInFileNames": true,
"outDir": "scripts",
"moduleResolution": "Node",
"experimentalDecorators": true
},
"$schema": "https://json.schemastore.org/tsconfig",
"exclude": [],
"include": [
"scripts/ts/**/*"
]
}
我的 main.ts 文件有這些導入:
import { css, html, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
main.ts 文件被編譯並且 main.js 被成功加載。 但我得到這個錯誤:
Uncaught TypeError: Failed to resolve module specifier "lit". Relative references must start with either "/", "./", or "../".
導入語句按“原樣”進行轉換。 它們在轉譯文件中看起來完全相同,所以我想問題是模塊路徑錯誤:瀏覽器不知道“lit”在“node_modules/lit”中,當我手動將轉譯文件中的路徑更改為../node_modules/lit/index.js 然后我得到另一個錯誤是
Uncaught TypeError: Failed to resolve module specifier "@lit/reactive-element". Relative references must start with either "/", "./", or "../".
我想這是一個由其他點亮模塊沿層次結構導入的模塊。 基本上我的導入路徑沒有正確轉換,我不知道該怎么做。 任何幫助都會很棒!
感謝@cdimitroulas 讓我思考這個問題。
ES6 導入需要有一個絕對或相對路徑——“普通節點導入”根本不起作用,這些路徑需要以某種方式解析,不僅針對主模塊的導入,而且針對依賴關系圖中的每個其他模塊的導入。
Typescript 編譯器無法處理此問題,因此當前設置缺少可以解析這些路徑(如 web-dev-server)或將模塊及其所有依賴項捆綁在一個文件中(如 webpack)的工具,從而無需解析路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.