Open eigood opened 2 years ago
This is how I solved the problem (requires node >= 17):
Created an esm-loader.mjs file in my root:
import { parse } from 'graphql';
import { promises as fs } from 'fs';
const VALID_EXTENSIONS = ['.graphql', '.graphqls', '.gql', '.gqls'];
export async function load(url, context, defaultLoad) {
const { pathname } = new URL(url);
const extension = pathname.slice(((pathname.lastIndexOf('.') - 1) >>> 0) + 2);
if (VALID_EXTENSIONS.includes(`.${extension}`)) {
const content = await fs.readFile(pathname, 'utf-8');
const parsed = parse(content);
const transformedSource = `export default ${JSON.stringify(parsed)};`;
return {
format: 'module',
source: transformedSource,
shortCircuit: true,
};
}
if (defaultLoad) {
return defaultLoad(url, context, defaultLoad);
} else {
throw new Error(`Unsupported file extension: ${extension}`);
}
}
Then you can do on the command line:
node --loader ./esm-loader.mjs src/index.js
If you're using typescript and ts-node:
TS_NODE_PROJECT=tsconfig.json node --loader ts-node/esm --loader ./esm-loader.mjs src/index.ts
Import in node when using *.mjs doesn't work, as import doesn't use require.extensions.