Reputation: 21
I have a React project that I want to start migrating the js files to typescript. The aliases that's set up works if I import .tsx inside another .tsx file but doesn't work if I try to import .js files inside the .tsx file.
// inside app.tsx
import Main from 'Components/main'; // works if main is a .tsx file but not .js
I get this error
Module not found: Error: Can't resolve 'Components/main'
It works if I do ./components/main.js but I want to use aliases.
webpack.config.js
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
alias: {
Components: path.resolve(__dirname, '/app/components/'),
},
},
rules: [
{
test: /\.ts|.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'thread-loader',
{ loader: 'babel-loader'}
],
},
},
//... other loaders
]
...
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"removeComments": true,
"baseUrl": ".",
"sourceMap": true,
"paths": {
"App": ["app"],
"Components/*": ["app/components/*"],
}
},
"include": [
"./app/"
],
"exclude": [
"./node_modules/"
]}
It would be great if I can use typescript path alias with js files. I set the allowJS to true inside the tsconfig.json but still no good.
Upvotes: 1
Views: 1759
Reputation: 21
I fixed it by using two loaders for Typescript files in webpack.
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'thread-loader',
{ loader: 'babel-loader'}
],
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: 'thread-loader',
},
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
options: {
happyPackMode: true,
}
},
],
},
Upvotes: 1