Solvedts loader ts-loader generating definition file in wrong directory

I am creating a new issue here as discussed in typescript Issue
I am using typescript version 1.9.0-dev.20160412 and ts-loader version 0.8.2 as below
My tsconfig.json is as below:

{
  "compileOnSave": false,
  "buildOnSave": false,
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "moduleResolution": "node",
    "preserveConstEnums": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "noEmitOnError": false,
    "forceConsistentCasingInFileNames": true,
    "removeComments": false,
    "sourceMap": true,
    "jsx": "react",
    "outDir": "./lib",
    "declaration": true
  },
  "exclude": [
    "node_modules",
    "dist",
    "typings/browser",
    "typings/browser.d.ts"
  ]
}

My project folder structure is as below:

work/
`-- projects
    `-- projectx
        |-- dist
        |-- src
        `-- tsconfig.json

I am trying to compile and generate .d.ts files inside the 'lib' dir but this creates the .d.ts file inside folder with parent attached to lib i.e

work/
`-- projects
    `-- projectx
        |-- src
        |-- dist
        |   `-- work
        |       `-- projects
        |           `-- projectx
        |               `-- dist
        |                   `-- lib
        |                       `-- src
        |                           `-- index.d.ts
        `-- tsconfig.json

I was expecting it to be as :

work/
`-- projects
    `-- projectx
        |-- dist
        |   `-- lib
        |       `-- src
        |           `-- index.d.ts
        |-- src
        `-- tsconfig.json 

dist dir above is given in the webpack.config.js as below:

output: {
    path: path.join(__dirname, '/dist'),
    filename: outputFile,
    library: libraryName,
    libraryTarget: 'umd',
    umdNamedDefine: true
  }

Sample project with the above mentioned error Sample Project.
It works as expected with the version 0.8.0 of ts-loader

31 Answers

✔️Accepted Answer

@johnnyreilly @gluons Sorry, my bad, you are right. Added the outDir to the compilerOptions and it works as expected.

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                options: {
                    compilerOptions: {
                        outDir: './dist'
                    }
                }
            }
        ]
    }

Thank you!

Other Answers:

@tedchirvasiu It works as intended in ts-loader v5. It's breaking change.
You have to set outDir or declarationDir to specify the output directory of declaration files.

From @JonWallsten in #882 :

I would have to say that it's intended (but maybe unwanted in some cases?). It's TypeScripts default behavior to do this. If you don't add outDir or declarationDir it might be intended, and you could get annoyed by a warning, since it's in the context of TypeScript isn't wrong.

Same issue in 4.2.0

Adding something like context: path.resolve("src") to the Webpack config is fixing this issue for me. Thanks @johnnyreilly!

Fixed on 0.9.3

Related Issues:

93
ts loader typescript v2.1.4 doesn't like empty files in config
Just ran into this issue and found a solution My loaders section in webpack looked like this: Turns ...
36
ts loader Can't resolve modules from node_modules with ts-loader; works with plain tsc
I solved it In webpack.config.js you need to explicitly add the extension .js to resolve.extensions ...
23
ts loader Can't use nullish coalescing operator with TypeScript 3.8.2
No It's not a bug It's a breaking change in the compiler behavior I changed the target to es2019 and...
23
ts loader ts-loader breaking when it's used with TS Path mappings based module resolution
Is it possible for ts-loader to get my information from paths in tsconfig.json and set them up as re...
21
ts loader ts-loader ignores exclude in webpack loader config
This is what I ended up doing: tsconfig.webpack.json Then for my loader I do ts-loader?configFileNam...
8
ts loader ts-loader generating definition file in wrong directory
@johnnyreilly @gluons Sorry my bad you are right Added the outDir to the compilerOptions and it work...
1400
TypeScript Quick fix for 'unions can't be used in index signatures, use a mapped object type instead'
You can do this: Though Bar has no index signature (i.e. you can't then do (obj as Bar)[value as Foo...
608
angular Angular5.x lazyLoad problem, undefined is not a function
For others that find this issue via Google as i did: I had the same problem when trying to lazy load...
595
react starter kit How to call child component method from parent?
For example you can use Refs to Components approach like so: Demo: https://jsfiddle.net/frenzzy/z9c4...
570
desktop The user name or passphrase you entered is not correct.
It sure looks like something's screwy with Keychain Try opening Keychain Access.app ...
568
431
ant design How to set 100% of height layout
This works for me: <Layout style={{height:100vh}}> I am a newbie I base on Meteor JS How to set 100%...
413
ant design Each record in table should have a unique key prop,or set rowKey to an unique primary key.
@ahmetkuslular The error message is pretty explicit your data set must contain items with a key prop...
397
material ui Module not found: Can't resolve 'material-ui-icons/Menu' Martial Next
For anyone else experiencing this issue: npm install @material-ui/icons https://www.npmjs.com/packag...
356
desktop Could not resolve host: github.com
Check this out as well it helped me. Description I create a new repository in my local and complete ...
348
angular Cyclic dependency error with HttpInterceptor
I resolved simply not setting authService in constructor but getting in the intercept function. ...
322
desktop It keeps saying The user name or passphrase you entered is not correct.
@tom10271 we think this is related to Keychain access due to some sort of macOS update: Try opening ...
310
DefinitelyTyped [@types/react] RefObject.current should no longer be readonly
It's not It'a intentionally left readonly to ensure correct usage even if it's not frozen ...
303
ts node Custom typings not working with ts-node 8.0.2
When using with ts-node you have to add --files flag After updating to ts-node version 8.0.2 the cus...
288
ngx admin No PostCSS Config found with build:prod
Or you can create a file named postcss.config.js in root directory Just leave it empty or write the ...
286
angular cli Issue: Cannot read property 'thisCompilation' of undefined
Here is the answer from issues #9793 : npm remove webpack npm install webpack@3.11.0 ...
280
react native template typescript can not run npx react-native init MyApp --template react-native-template-typescript
Just remember to npm uninstall -g react-native-cli and yarn global add @react-native-community/cli s...
277
angular Uncaught Error: Can't resolve all parameters for ...
You are missing an @Injectable() annotation on your ApiService Support requests like these should li...
266
angular Force reload/refresh current route with RouteReuseStrategy
Hi If you really need to trick the Router into reloading the component on each routerLink click ...
260
angular Misleading error message "Cannot find a differ supporting object '[object Object]'"
I just ran into the same issue I'm not sure if the recommended solution will work for my case ...
255
angular cli Error | Could not find plugin "proposal-numeric-separator" | Generating ES5 bundles for differential loading
Try to install @babel/compat-data: ~7.8.0 to devDependencies This is the only workaround which helpe...
255
react hook form How to submit the form outside the form
For those who come across this issue like I did and found it didn't quite address the question ...
239
apollo client Store error: the application attempted to write an object with no provided id but the store already contains an id of...
Hey @hinok 👋 This error only should occur when you have made a query with an id field for a portion...
236
angular cli Using invalid environment causes error in build (was "ERROR in Cannot read property 'length' of undefined")
Probably not the same cause but we had the same error (Cannot read property 'length' of undefined) w...
232
angular cli ng serve method ip not open in another machines
The solution is simple Just bind to the correct interface address via ng serve --host=0.0.0.0 ...
226
angular cli Incorrect JS paths when ng build -prod is deployed in a subfolder
When you're deploying to non-root path within a domain you'll need to manually update the <base href...
224
angular update 2 to 4 has problem [ts] Property 'map' does not exist on type 'Observable<Response>'.
I met the same problem with the angular cli 6.0.0 and rxjs 6.1.0 And I solved the problem by replaci...
219
desktop A lock file already exists in the repository, which blocks this operation from completing.
@simhox thank you for updating the issue body and uploading the log file! Here's the related error: ...
218
angular cli Installation error: permission denied for node-sas
sudo npm install -g --unsafe-perm --verbose @angular/cli Installation error (node-sass) with: node v...
209
vscode cpptools can't stop at the breakpoint
@Sendoushi @andychen2016 Please confirm when you are compiling that you are compiling with the -g fl...
208
angular cli ng build -prod Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory'
Instead of use ng build --prod use ng build --env=prod UPDATE As many of us (thx) have mention this ...
207
vscode restclient Header name must be a valid HTTP token ["{"]
OK looks like the error is: where as this is OK: I had a previous simple test file that was working ...
199
vscode macOS Mojave: font rendering is blurry or has changed
So.. Mojave is out The font rendering looks awful on both 1x displays and Retina displays I'm really...
186
vuetify [Bug Report] Could not find a declaration file for module 'vuetify/lib'
@KaelWD Thank you for the link More specifically this comment helped me out to properly update my ts...
179
TypeScript "Ignore this error message" code fix in JSX results in rendering // @ts-ignore
(unless we really think something like is OK?) TypeScript Version: 3.2.0-dev.20181004 Search Terms: ...
175
storybook Webpack 4 support?
I'm getting the below error when running Storybook with a project using Webpack 4; This is preventin...
173
angular cli Property 'controls' does not exist on type 'AbstractControl'.
Got it! Looked at the docs - FormArray The FormArray class contains the controls property ...
173
TypeScript Suggestion: Add abstract static methods in classes and static methods in interfaces
I want to force implementation of static deserialize method in Serializable's subclasses Is there an...
172
apollo client Catching Network error: Converting circular structure to JSON
To anyone else coming here I ran into this doing Ran into the issue because the onClick event object...
171
ts jest Jest encountered an unexpected token
@mohsinulhaq I was able to fix the error similiar to yours by changing jsx property of tsconfig.json...
171
TypeScript Creating types from values in array
in ts@3.x and above solve it like this TypeScript Version: 3.0.3 Search Terms: Type based on values ...
170
angular Angular2 AoT Compiler Errors
pls try /cc @chuckjaz When I try to compile my project with ngc it throws the below error: Error: Er...
169
react hook form Ability to disable submit button until valid form
Add formState api then in your button Is your feature request related to a problem? Please describe ...
167
angular cli [Bug] cli needs to be reloaded when a lazy loaded module is added in routes (FIXED)
I recomended change { path: 'user-panel' loadChildren: './user-panel/user-panel.module#UserPanelModu...
167
prettier Change HTML/JSX formatting to have one attribute/prop per line
The point I am trying to make is that the vertical space matters Wasting it (too much) has negative ...