[英]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.