0

tsc nearly works but I can't get it to output .mjs files. swc doesn't want to output .mjs nor the .d.ts files.

Is there a comprehensive bundler that'll do both?

Ideally I want to point it at my index.ts file which just looks like this

export * from './map'
export * from './set'
export * from './array'

And then it will find the other files and compile them. Anything not in the import/export chain should be omitted from the output, but if I have to compile my entire src dir I can live with that.


Additional constraints:

I think I can work around the .mjs file extension by adding "type": "module" to package.json. But I still need the import/export statements to be re-written properly (with extension)

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • Did you see this https://github.com/microsoft/TypeScript/issues/18442#issuecomment-1073060190 ? – yevt Dec 29 '22 at 19:58
  • Yeah, I saw that comment a few minutes ago and `swc` isn't working for me either (2nd sentence of my Q) – mpen Dec 29 '22 at 20:00

1 Answers1

0

OK, I think I got it. The answer is Rollup.

yarn add --dev rollup @rollup/plugin-typescript @rollup/plugin-terser tslib
// rollup.config.js
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';

export default {
    input: 'src/index.ts',
    output: {
        dir: 'dist',
        format: 'esm',
        entryFileNames: '[name].mjs'
    },
    plugins: [
        typescript(),
        terser({
            format: {
                comments: 'some',
                beautify: true,
                ecma: '2022',
            },
            compress: false,
            mangle: false,
            module: true,
        }),
    ]
};
// package.json
{
  "name": "@you/your-package",
  "version": "0.1.11",
  "packageManager": "yarn@3.3.1",
  "main": "dist/index.mjs",
  "type": "module",
  "types": "dist/index.d.ts",
  "files": [
    "/dist"
  ],
  "scripts": {
    "build": "rollup -c",
    "test": "jest --silent=false",
    "publish-patch": "npm version patch && hg ci -m \"Publish v$(jq -r '.version' package.json)\" && npm publish"
  },
  "devDependencies": {
    "@rollup/plugin-terser": "^0.2.1",
    "@rollup/plugin-typescript": "^10.0.1",
    "@types/jest": "^29.2.4",
    "jest": "^29.3.1",
    "rollup": "^3.9.0",
    "ts-jest": "^29.0.3",
    "tslib": "^2.4.1",
    "typescript": "^4.9.4"
  }
}

That will output files with .mjs extension and include the .d.ts files and omit other junk in your src dir like test files.

Terser is needed if you want to strip comments from the output. The import/export file extension renaming is no longer relevant because Rollup insists on outputting a single file.

tslib is needed to make rollup happy. So is type: "module" even though TS doesn't care, and nor does Node if you use .mjs extension.

mpen
  • 272,448
  • 266
  • 850
  • 1,236