Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TypeScript boilerplate #78

Merged
merged 2 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 42 additions & 3 deletions src/assets/createScript.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
const VALID_FILENAME = /^[^0-9.#<>$+%!`&='{}@\\/:*?"|\n][^#<>$+%!`&='{}@\\/:*?"|\n]*$/;
const extensionToBoilerplateMap = new Map([
['.js', createBoilerplate],
['.mjs', createEsmBoilerplate],
['.ts', createTsBoilerplate]
]);
const validExtensions = Array.from(extensionToBoilerplateMap.keys());

/**
* Creates filename and script content from provided arguments. If the provide filename contains a '.mjs'
Expand Down Expand Up @@ -49,11 +55,17 @@ function createScript(filename, text) {
filename = `${scriptName}.js`;
}

if (!/.js$/i.test(filename)) {
const hasValidExtension = validExtensions.some(ext => filename.endsWith(ext));
if (!hasValidExtension) {
filename += '.js';
}
const isEsm = filename.endsWith('.mjs');
const boilerPlateGenerator = isEsm ? createEsmBoilerplate : createBoilerplate;

// Extract extension from filename
const extension = filename.slice(filename.lastIndexOf('.'));

// Get the correct boilerplate generator based on the file extension
const boilerPlateGenerator = extensionToBoilerplateMap.get(extension);

const content = text || boilerPlateGenerator(className, scriptName);

return {
Expand Down Expand Up @@ -112,4 +124,31 @@ export class ${className} extends Script {
`.trim();
}

function createTsBoilerplate(className, scriptName) {
return `
import { Script } from 'playcanvas';

/**
* The {@link https://api.playcanvas.com/classes/Engine.Script.html | Script} class is
* the base class for all PlayCanvas scripts. Learn more about writing scripts in the
* {@link https://developer.playcanvas.com/user-manual/scripting/ | scripting guide}.
*/
export class ${className} extends Script {
/**
* Called when the script is about to run for the first time.
*/
initialize(): void {
}

/**
* Called for enabled (running state) scripts on each tick.
*
* @param {number} dt - The delta time in seconds since the last frame.
*/
update(dt: number): void {
}
}
`.trim();
}

export { createScript };