Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript relative path import not working in Webpack

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
like image 700
fafaro Avatar asked Jul 31 '17 01:07

fafaro


1 Answers

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.

like image 189
fafaro Avatar answered Nov 15 '22 03:11

fafaro