I am currently working on developing a webpack loader that can transform a file containing API data structure descriptions into TypeScript interfaces.
Specifically, the file format I am using is JSON, but this detail should not be crucial as the file serves as a common source of information outlining the communication between web application backend(s) and frontend(s). In the sample code provided below, you will notice that the JSON file includes an empty object to emphasize that the content of the file does not impact the issue at hand.
My current implementation is encountering two errors (with the assumption that the first error is leading to the second one):
[at-loader]: Child process failed to process the request: Error: Could not find file: '/private/tmp/ts-loader/example.api'.
ERROR in ./example.api
Module build failed: Error: Final loader didn't return a Buffer or String
What steps can I take to generate TypeScript code using a webpack loader?
package.json
{
"name": "so-example",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "webpack"
},
"dependencies": {
"awesome-typescript-loader": "^3.2.3",
"typescript": "^2.6.1",
"webpack": "^3.8.1"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './index.ts',
output: {
filename: 'output.js',
},
resolveLoader: {
alias: {
'my-own-loader': path.resolve(__dirname, "my-own-loader.js"),
},
},
module: {
rules: [
{
test: /\.api$/,
exclude: /node_modules/,
use: ["awesome-typescript-loader", "my-own-loader"],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: "awesome-typescript-loader",
},
]
},
};
my-own-loader.js
module.exports = function(source) {
return `
interface DummyContent {
name: string;
age?: number;
}
`;
};
index.ts
import * as foo from './example';
console.log(foo);
example.api
{}
I understand that there are alternative methods for generating code, such as converting JSON files to TypeScript using a build tool and then committing them. However, I am interested in exploring a more dynamic solution.
my-own-loader.js does not export json but string.
Indeed, similar to how loading an image file might not always result in exporting binary data but instead produce a JavaScript representation of metadata about the image.
Why do you need to define TypeScript interfaces from a JSON file? Will these interfaces be utilized during TypeScript compilation?
Yes, the goal is to import a file detailing the API data structures and automatically derive the corresponding TypeScript interfaces. By using a shared file, both frontend(s) and backend(s) can maintain consistency on the expected data format.