0

(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)

Ziyuan
  • 4,215
  • 6
  • 48
  • 77
  • Can you try `"include": ["./*","**/*"],` in your tsconfig please? – Raz Ronen Aug 11 '20 at 09:36
  • @RazRonen No it doesn't help – Ziyuan Aug 11 '20 at 09:37
  • Can you try changing `target` in tsconfig to `es5`? Either that or you'll need to add `babel-loader` to compile javascript esnext to javascript es5. – Raz Ronen Aug 11 '20 at 09:44
  • 2
    @RazRonen Oh actually `resolve: { extensions: [".ts", ".tsx", ".js"] }` is what I am missing in `webpack.config.js` after realizing `ts-loader` is the problem (mentioned in your deleted answer). Now it works. Thanks. – Ziyuan Aug 11 '20 at 10:09

0 Answers0