1

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.

1 Answer 1

1

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,
            }
        },
    ],
},
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.