Francesco Borzi
Francesco Borzi

Reputation: 61724

Webpack and TypeScript: Module not found: Error: Cannot resolve 'file' or 'directory'

I'm trying to compile TypeScript using Webpack, but for some reasons it fails on imports:

ERROR in ./path/to/MySource.ts Module not found: Error: Cannot resolve 'file' or 'directory' ./path/to/MyIncludedFile in ...

despite MyIncludedFile.ts is actually there and the IDE can recognise the import too, the TypeScript compiler doesn't find the file.

Upvotes: 0

Views: 5151

Answers (2)

Roberto
Roberto

Reputation: 713

I ran into this error, too and also tried it with --display-error-details (in newer webpack versions the parameter has a trailing s!).

Turned out I forgot the dots in my extensions array. Adding them resolved the issue.

resolve: {
  extensions: ['.ts', '.tsx', '.js']
//              ^      ^       ^
//              |      |       |
//           don't forget these dots!
}

Sometimes it's the tiny details and a giant error log that leads to the solution, I guess. Hope it helps someone in the future.

Upvotes: 5

Francesco Borzi
Francesco Borzi

Reputation: 61724

Running Webpack with --display-error-detail I got some extra information:

/path/to/MyIncludedFile doesn't exist
/path/to/MyIncludedFile.webpack.js doesn't exist
/path/to/MyIncludedFile.web.js doesn't exist
/path/to/MyIncludedFile.js doesn't exist
/path/to/MyIncludedFile.json doesn't exist

because of that, I realised that Webpack wasn't looking for the correct extension, which in my case is .ts.

In order to solve that I modified my webpack.config.js adding the following:

resolve: {
    extensions: ['.ts']
}

inside my module configuration. So to be more specific, my module webpack conf now look like this:

module.exports = [
  {
      entry: /* my entry config */
      output: {
          /* my output config */
      },
      module: {
          loaders: [
              {
                  test: /\.ts/,
                  loaders: ['ts-loader']
              }
          ]
      },
      /* ... other stuff ... */
      resolve: {
          extensions: ['.ts']
      }
  },
  /* ... other modules ... */
]

Upvotes: 8

Related Questions