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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With