webpack ts-loader error : loaderContext.getOptions is not a function

Viewed 24112

I'm trying to import my typescript file into webpack, when I run tsc in my terminal everything works fine, But when I try to use compile my typescript code in ts-loader this weird error is shown :

ERROR in ./src/Main.ts
Module build failed (from ./node_modules/ts-loader/index.js):
TypeError: loaderContext.getOptions is not a function
    at getLoaderOptions (D:\Projects\Real\AviUI\node_modules\ts-loader\dist\index.js:91:41)
    at Object.loader (D:\Projects\Real\AviUI\node_modules\ts-loader\dist\index.js:14:21)

the webpack version : 4.43.0, the ts-loader version : ^9.2.3 , the loader-utils version: ^1.4.0

webpack.config.js file :

module.exports = {
    entry: path.resolve(__dirname, './src/main.ts'),
    module: {
        rules: [ 
        {
            test: /\.ts$/,
            include: [source_path],
            loader: 'ts-loader',
            exclude: /node_modules/, 
        }],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: 'avi_ui.js',
        path: path.resolve(__dirname, 'dist')
    },
    externals: {
        'jquery': '`jquery`',
        'angular' : '`angular`'
    },
    mode: 'development'
};

NOTE : I tried to update my typescript compiler to latest version(currently latest version is: 4.3.3) but it didn't work for me.

2 Answers

There is one more way to solve the problem, in addition to upgrading your webpack to webpack 5, as Ali Bigdeli's answer pointed out. You can also just downgrade ts-loader to 8.2.0. Using your package manager of choice, that might look like:

npm install ts-loader@~8.2.0

As pointed out in the Github question linked by Ali Bigdeli, the last version of ts-loader that supports webpack 4 is 8.2.0, and if you want to receive patches to this version, you can depend on the semver ~8.2.0 version.

According to Github question the only way to solve this problem is upgrade the webpack to v5.
I found this link from webpack official website. The easiest way to upgrade version is using your javascript package manager , for exampele if your using npm or yarn the following terminal codes can be used :

# using npm 
$ npm install webpack@5.40.0
# using yarn
$ yarn add webpack@5.40.0

NOTE: In this time current version of webpack is 5.40.0

Related