如何解决在Typescript Node.js应用中导入变量时无法解析本地模块
( UPDATE :已解决。我必须在webpack.config.js
中添加可解析的扩展名,例如,以resolve: { extensions: [".ts",".tsx",".js",".mjs"] }
的形式添加,尽管不确定导入接口为何起作用。{{3 }}。
项目结构:
.
├── global.ts
├── index.ts
├── node_modules
├── package.json
├── tsconfig.json
├── webpack.config.js
└── yarn.lock
和文件内容:
// global.ts
// has more than one exported variables in the real project
export const g: string = "g";
// index.ts
import { g } from "./global";
console.log(g);
// tsconfig.json
{
"include": ["**/*"],"exclude": ["node_modules/*"],"compilerOptions": {
"target": "esnext","module": "esnext","sourceMap": true,"strict": true,"noImplicitAny": true,"moduleResolution": "node","types": [
"node"
],"allowSyntheticDefaultImports": true,"esModuleInterop": true
}
}
// webpack.config.js
module.exports = {
target: "node",entry: {
index: "./index.ts",},output: {
filename: "[name].js",module: {
rules: [
{
test: /\.ts$/,use: "ts-loader",exclude: /node_modules/,],};
// package.json
{
"name": "app","version": "1.0.0","main": "index.ts","license": "MIT","devDependencies": {
"@types/node": "^14.0.27","ts-loader": "^8.0.2","typescript": "^3.9.7","webpack": "^4.44.1","webpack-cli": "^3.3.12"
}
}
然后如果我npx webpack
我会得到
ERROR in ./index.ts
Module not found: Error: Can't resolve './global' in <full-path-to-app>
@ ./index.ts 1:0-29 2:12-13
但是,如果我改为从./global.ts
导入已声明的接口,则不会有错误。说,
// global.ts
export interface Dict {
[key: string]: string
}
// index.ts
import { Dict } from "./global";
const d: Dict = { key: "value" };
console.log(d);
这很好。那么,这里出了什么问题? (为方便起见,创建了Reference)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。