5

I imported a module in TypeScript using a relative path.

// index.ts
import {Widget} from './components/Widget';

Webpack gives me the following error:

ERROR in ./src/index.ts
Module not found: Error: Can't resolve './components/Widget' in 
C:\project\src' @ ./src/index.ts 4:19-51

My webpack config file is pretty basic, with the ts-loader in the rules and pointing to index.ts as the entry file.

What am I doing wrong here?


Additional information:

Project folder structure:

c:\project
├─ src
│  ├─ index.ts
│  └─ components
│     └─ Widget.ts
├─ webpack.config.js
└─ tsconfig.json

Webpack config:

const path = require('path');

const config = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      { test: /\.tsx?$/, use: 'ts-loader' }
    ]
  }
};

module.exports = config;

tsconfig.json

{
    "compilerOptions": {
        "outDir": "dist",
        "module": "commonjs",
        "target": "es6"
    },
    "include": [ "src/**/*" ],
    "exclude": [
        "node_modules"
    ]
}

Versions:

webpack 3.1.0
typescript 2.4.1
ts-loader 2.2.2
5
  • Where is your webpack.config.js file located? Commented Jul 31, 2017 at 3:01
  • @Saravana I've added the info to the project structure in the answer. Commented Jul 31, 2017 at 4:43
  • 1
    Can you post your tsconfig.json? This should work as long as you don't have any path mapping in your tsconfig.json. Commented Jul 31, 2017 at 7:27
  • @Saravana Add tsconfig. The project builds perfectly find with the TypeScript compiler (tsc). Commented Aug 1, 2017 at 3:28
  • did you export Widget class in Widget.ts?also i which file are you trying to import your class ? Commented Aug 1, 2017 at 3:41

1 Answer 1

13

Add resolve.extensions to your webpack.config.js.

{
    resolve: {
        extensions: ['.ts', '.js', '.json']
    }
}

Module resolution in webpack defaults to searching only for .js and .json files when you write an extension-less import in one of your modules (ref).

So when you write:

import {Widget} from './components/Widget';

Webpack only searches for these files by default:

./components/Widget.js
./components/Widget.json

and thus ends up giving the Module not found error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.