angularmigrationcommonjsangular18

Migrating Angular 13 to Angluar 18


I am using with angular 13

https://github.com/bbc/slayer

Its a commonjs lib and has no @types.I Managed to make it work with angular 13 (a while back) but now with the vite compiler I just dont know how. I added "types": ["node"] to tsconfig.json and tsconfig.app.json add declared a type.d.ts declare module 'slayer'; but nothing works

ReferenceError: process is not defined
    at node_modules/slayer/node_modules/readable-stream/lib/_stream_writable.js

How can I import properly a commonjs module in my angluar 18 app ? Thanks


Solution

  • I have created a reference example. Tell me know if you need more help.
    Slayer example Angular 18

    src/app/slayer.d.ts

    declare module 'slayer' {
          export interface SlayerConfig {
            minPeakDistance: number;
            minPeakHeight: number;
            transformedValueProperty: string;
          }
          export class Slayer {
            constructor(config: SlayerConfig);
            fromArray(array: number[]): Promise<any>;
    
            // add other methods that you need
          }
        }
    

    ...

    src/app/process.d.ts

    declare module 'process';
    

    angular.json

    "builder": "@angular-devkit/build-angular:application";
    

    to

    "builder": "@angular-devkit/build-angular:browser"
    

    Change browser to main

    "browser": "src/main.ts"; => "main": "src/main.ts";
    

    Add polyfills.ts

    "polyfills": ["src/polyfills.ts"]
    

    Create file src/polyfills.ts

    import 'zone.js';
    ...
    
    (window as any).process = {
        env: { DEBUG: undefined },
        version: '', // to avoid undefined.slice error
    };
    

    declare in tsconfig.app.json

    "files": [
        "src/main.ts",
        "src/polyfills.ts" // <= add
    ]
    

    Install

    npm install util