Emit TypeScript modules as separate JavaScript files
Asked Answered
D

0

9

I'm authoring a library and I want to provide both a bundle (where all files are compiled together) and a js folder where each module is emitted separately with its .d.ts file next to it. My goal is to allow:

  1. Using separate files as TS modules from the src folder
  2. Using files as JS modules from the js folder when you don't want to compile TypeScript
  3. Using the bundle when you don't want to compile anything at all

I'm using ts-loader to compile a bunch of TypeScript modules with the following webpack.config.js:

let path = require('path')

module.exports = {
  entry: {
    main: './src/index.ts'
  },
  output: {
    path: path.resolve(__dirname, 'js')
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader'
      }
    ]
  }
}

...and the following tsconfig.json:

{
  "compilerOptions": {
    "outDir": "js",
    "module": "commonjs",
    "target": "es5",
    "lib": [
      "es2015",
      "dom",
      "dom.iterable"
    ],
    "declaration": true,
    "strictBindCallApply": true,
    "downlevelIteration": true
  }
}

With this setup, running webpack results in a bundle and all .d.ts files in a js folder, which is in the middle of what I want. I need each .ts file in the dependency graph to be emitted next to its .d.ts file as a .js file instead. Essentially, I need two Webpack configs:

  • one that emits .js and .d.ts files in a directory structure that mirrors src
  • another one that emits just a bundle

Before publish, I run both configurations and I get all I need. However, I can't get ts-loader to emit separate .js files. Is it possible?

Drandell answered 10/12, 2019 at 7:48 Comment(3)
@T.J.Crowder yeah, I don't know why it's es3 either. It made no sense. Changed it to es5. Thanks!Drandell
What is the answer for this question? Did you solve it?Humble
I have asked a similar question with no answer either.Giffy

© 2022 - 2024 — McMap. All rights reserved.