![](/img/trans.png)
[英]Typescript can't find modules which are imported with webpack alias
[英]About nodejs path in webpack, how webpack find modules in typescript?
我使用 webpack-dev-server 來解析一些打字稿。
我的配置文件:
module.exports={
entry: "./src/index.ts",
output: {
filename: "main.js"
},
resolve:{
extensions: ['.ts', '.tsx', 'js'],
modules: [path.resolve(__dirname, 'src'), "node_modules"]
}
...
}
然后命令行的output:
> cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js
i 「wds」: Project is running at http://localhost:8089/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from ./dist
× 「wdm」:
ERROR in (webpack)-dev-server/client?http://localhost:8089
Module not found: Error: Can't resolve './overlay' in 'F:\workspace\tslearn\node_modules\webpack-dev-server\client'
@ (webpack)-dev-server/client?http://localhost:8089 10:14-34
@ multi (webpack)-dev-server/client?http://localhost:8089 ./src/index.ts
webpack-dev-server\client.js 中的 index.js 是:
var stripAnsi = require('strip-ansi');
var socket = require('./socket');
var overlay = require('./overlay');
var _require = require('./utils/log'),
./overlay.js 位於路徑“F:\workspace\tslearn\node_modules\webpack-dev-server\client”下
但是js還是找不到。
vscode給我的指示是:
Could not find a declaration file for module './socket'. 'f:/workspace/tslearn/node_modules/webpack-dev-server/client/socket.js' implicitly has an 'any' type.
如何解決? Typescript 和 JavaScript 有什么不同?
背景
Webpack itself doesn't deal with Typescript, it uses a helper such as ts-loader or other depending on the webpack configuration file webpack.config.js
. 配置示例:
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
happyPackMode: true,
configFile: path.resolve(__dirname, 'tsconfig.json'),
},
}
],
},
...
other rules
...
]
ts-loader 將使用 tsconfig.json 中的配置設置tsconfig.json
。
如何解決? Typescript 和 JavaScript 有什么不同?
tsconfig.json
應該有"allowJs": true
否則 Typescript 編譯器在解析導入時不會考慮.js 文件。 此外 Typescript 編譯器應該能夠找到overlay.js
和 other.js 文件。 它將在TypeScript 如何解析模塊標題下記錄的幾個地方進行搜索。
最后,為了擺脫與聲明相關的錯誤,編寫聲明文件,例如overlay.d.ts
並將其放在相應的.js 文件旁邊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.