I am attempting to create a webpack loader that converts a file containing a description of API data structures into a set of TypeScript interfaces.
In my concrete case, the file is JSON, but this should be ultimately irrelevant — the file is only a shared source of data describing the interaction between web application backend(s) and frontend(s). In my MCVE below, you can see that the JSON file contains an empty object to underscore how the type and contents of the file do not matter to the problem.
My current attempt reports two errors (I assume the second is caused by the first):
[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
How can I 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 recognize that there are other code generation techniques. For example, I could convert my JSON files to TypeScript with some build tool and check them in. I'm looking for a more dynamic solution.
my-own-loader.js does not export json but string.
That's correct, much like loading an image file doesn't always export binary data but sometimes outputs a JavaScript data structure representing metadata about the image.
Why you need to define the typescript interfaces from json file? Would the interfaces be used for typescript compilation?
Yes. I want to import a file that describes my API data structures and automatically generate corresponding TypeScript interfaces. Having a shared file allows the frontend(s) and backend(s) to always agree on what data will be present.