Sunday, 14 May 2017

VS Code AMD Module System

I'm working on an Electron application using TypeScript and I'm running into some issues while trying to figure out the module loading system to use. I have been digging through the VS Code code (since many consider it the "poster child" for Electron apps done right) in order to get a better understanding of conventions/the best ways to do certain things, and I've noticed that they are using AMD modules (in the tsconfig.json file under src, the options "module": "amd", "moduleResolution": "classic", and "baseUrl": "." are all set) and they seem to be using requirejs-like calls for certain things, such as loading the URL into the BrowserWindow, where they use require.toUrl('vs/workbench/electron-browser/bootstrap/index.html'); to get the full URL to load.

From my (admittedly limited) understanding, this solves a problem that I am running into where I compile my TypeScript (located in the src directory) to an output directory (called out) then provide the .js files to Electron to execute, meaning that my paths for things like mainWindow.loadUrl(__dirname + '/index.html') suddenly point to out/index.html instead of the intended src/index.html. However, as I'm searching through the VS code project for any reference to the requirejs module, I can't find anything except a require.d.ts file containing this code

declare var define: {
    (moduleName: string, dependencies: string[], callback: (...args: any[]) => any): any;
    (moduleName: string, dependencies: string[], definition: any): any;
    (moduleName: string, callback: (...args: any[]) => any): any;
    (moduleName: string, definition: any): any;
    (dependencies: string[], callback: (...args: any[]) => any): any;
    (dependencies: string[], definition: any): any;
};

declare var require: {
    toUrl(path: string): string;
    (moduleName: string): any;
    (dependencies: string[], callback: (...args: any[]) => any, errorback?: (err: any) => void): any;
    config(data: any): any;
    onError: Function;
    __$__nodeRequire<T>(moduleName: string): T;
};

I've created a typings file containing this within my project, but I'm getting a define is not defined error when running my transpiled JavaScript. My question is: how exactly is VS Code able to use AMD modules with the standard Node require module, seemingly without using something like requirejs, and could implementing a similar pattern solve my path problems when running the transpiled JavaScript code from an output directory? Thanks!



via M. Bise

No comments:

Post a Comment