Open joaofranciscosantos opened 1 year ago
好像不能用import都要用require
Note that the file is auto-generated. It should not be modified manually
I am having the same issue in Deno. It is very problematic because the ESM module specification explicitly disallows imports without the file extension, so there are a lot of environments that do not support these imports.
This should be reopened as the fix was reverted. This needs to be adressed somehow as esm won't go anywhere :)
Thanks, I'll take a look at the reasons for the revert as soon as I have a chance and see if I can help out somehow.
Meanwhile, I figured a simple codemod that would make the generated files to be ESM-compatible. Hopefully, some would find this useful:
npx proto-loader-gen-types --longs=String --enums=String --defaults --oneofs --grpcLib=@grpc/grpc-js --outDir=src/protos/generated/ src/protos/*.proto
Use codemod
proto-codemod.js
import { readFileSync, readdirSync, writeFileSync } from 'fs';
import { join } from 'path';
const relativePathToDirArg = process.argv[2];
const absolutePathToDir = join(import.meta.dirname, relativePathToDirArg);
readdirSync(absolutePathToDir, { recursive: true })
.filter((/** @type {string} */ filename) => filename.endsWith('.ts'))
.forEach((filename) => {
const pathToFile = join(absolutePathToDir, filename);
const file = readFileSync(pathToFile, { encoding: 'utf-8' });
// Looking for all relative import paths and appending ".js" to the end of the import path
const modifiedFile = file.replaceAll(/(import .* '\.+\/.*)';/g, "$1.js';");
writeFileSync(pathToFile, modifiedFile);
});
Run with node proto-codemod.js ./src/protos/generated
💡 make sure to replace the paths to generated files with yours
Environment
Problem description
The generated file(s) are not compatible with ES modules.
Reproduction steps
"type": "module"
"module": "node16", "moduleResolution": "node16"
How to Fix
The generated import should end with ".js": (See image below)
Additional context
Current error:
Proto file:
Image with error: