(UPDATE: solved. I have to add the resolvable extensions in webpack.config.js
, for example, as resolve: { extensions: [".ts", ".tsx", ".js", ".mjs"] }
, although not sure why importing interfaces works. Reference.)
Project structure:
.
├── global.ts
├── index.ts
├── node_modules
├── package.json
├── tsconfig.json
├── webpack.config.js
└── yarn.lock
and the file contents:
// 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"
}
}
Then if I npx webpack
I will get
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
But if I instead import the declared interfaces from ./global.ts
, there will be no errors. Say,
// global.ts
export interface Dict {
[key: string]: string
}
// index.ts
import { Dict } from "./global";
const d: Dict = { key: "value" };
console.log(d);
This works fine. So what goes wrong here? (a gist is created for convenience)