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

feat: transpile .ts imports #92

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
32 changes: 19 additions & 13 deletions handlers/importHandler.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
const fs = require('fs');
const path = require('path');
const ts = require('typescript');

module.exports = function importHandler(value, context, request) {
if (!/^#import/m.test(value)) return value;
if (!/^#import/m.test(value)) return value;

return value
.replace(/^#import (.*);/m, function (includeStatement, file) {
const importThisFile = file.replace(/['"]/g, '');
const content = fs.readFileSync(path.join(context, importThisFile));
if (importThisFile.endsWith('.js')) {
return JSON.stringify(eval(content.toString()));
} else {
return content;
}
})
.replace(/\r\n?/g, '\n');
}
return value
.replace(/^#import (.*);/m, function (includeStatement, file) {
const importThisFile = file.replace(/['"]/g, '');
const content = fs.readFileSync(path.join(context, importThisFile));
if (importThisFile.endsWith('.ts')) {
const { outputText } = ts.transpileModule(content.toString(), {
compilerOptions: { module: ts.ModuleKind.CommonJS },
});
return JSON.stringify(eval(outputText));
} else if (importThisFile.endsWith('.js')) {
return JSON.stringify(eval(content.toString()));
} else {
return content;
}
})
.replace(/\r\n?/g, '\n');
};
5 changes: 5 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"colors": "^1.3.2",
"header-case-normalizer": "^1.0.3",
"js-combinatorics": "^0.5.0",
"typescript": "^4.0.2",
"yargs": "^12.0.1"
},
"devDependencies": {
Expand Down
4 changes: 4 additions & 0 deletions test/mocks/importts/GET.mock
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
HTTP/1.1 200 OK
Content-Type: application/json

#import './script.ts';
5 changes: 5 additions & 0 deletions test/mocks/importts/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const dateResponse = {
date: new Date(),
};

export default dateResponse;
Loading