[英]Is there a way to add typings to an externally included javascript file in typescript?
對於上下文; 我正在制作一個客戶端腳本,我厭倦了等待 webpack 在我進行更改時捆綁我的所有依賴項。 因此,我通過 html 文件中的<script>
標記添加了依賴項,但是,我無法找到一種向依賴項創建的全局變量添加類型的方法。
例如:
在我的 html 中,我像這樣包含 d3:
<script src="https://cdn.jsdelivr.net/npm/d3@5.15.0/dist/d3.min.js"></script>
在我的index.ts
文件中,我有以下內容:
declare const d3; // currently has the <any> type
//I do stuff with d3 down here
這工作正常。 但是,D3 是一個龐大的庫,並且智能感知幫助了很多,所以我不會經常查看他們令人困惑的文檔。 我希望能夠像這樣包含我的打字文件:
import type d3 from 'd3'
declare const d3:d3;
但是,該錯誤是因為它與我的本地聲明沖突。
總之
有沒有人有將類型應用於外部包含的 javascript 文件的好方法?
[編輯]我在下面包含了我的 package.json 文件以顯示我正在使用哪些技術。 真的不多。
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack -w"
},
"keywords": [],
"author": "Michael Sorensen",
"license": "ISC",
"dependencies": {
// I'm including the dependencies that were here in my html file
},
"devDependencies": {
"@types/chart.js": "^2.9.16",
"@types/d3": "^5.7.2",
"@types/geojson": "^7946.0.7",
"@types/papaparse": "^5.0.3",
"ts-loader": "^6.2.2",
"typescript": "^3.8.3",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-node-externals": "^1.7.2"
}
}
如果您的編輯器支持.d.ts
類型文件,您應該可以在以下位置找到:
因此,如果您在 SO @Erik Phillips 上找到這篇文章,那么您的答案可能就是您要尋找的答案。
但是,就我而言,我只是錯誤地設置了我的 webpack。 我需要手動定義我的外部模塊,而不是使用 node_externals webpack 插件。
我的 webpack.config.js 文件現在看起來像這樣:
module.exports = {
mode: "production",
entry: "./src/index.ts",
devtool: "inline-source-map",
externals: [
{
d3: "d3",
"chart.js": "Chart",
papaparse: "Papa",
}
], // in order to ignore all modules in node_modules folder
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".json"]
},
output: {
filename: "index.js",
path: path.resolve(__dirname, "build")
}
};
現在,我可以捆綁我的打字稿文件而不包括提到的庫,同時不改變它們的導入方式。 現在看起來很明顯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.