jscodeshift
jscodeshift copied to clipboard
throw error when i try to generate an ExportSpecifier by j.exportSpecifier API
I'm going to convert javascript to typescript, so replace commonJS with ESmodule by ast plugin. But there is something wrong with the generator function jscodeshift.exportSpecifier().
Here's the demo code:
source.js
const VirtualMachine1 = require('./virtual-machine');
module.exports = VirtualMachine1;
plugin.js
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ExpressionStatement, {
expression: {
operator: '=',
left: {
object: {
name: 'module',
},
property: {
name: 'exports',
},
},
},
})
.forEach(path => {
const varName = path.value.expression.right.name;
const replaceDeclaration = j.exportNamedDeclaration(null, [
j.exportSpecifier(j.identifier(varName), j.identifier(varName)),
]);
j(path).replaceWith(replaceDeclaration);
}).source
}
The Error message is 'no value or default function given for field "exported" of ExportSpecifier("id": Identifier | null, "name": Identifier | null)', But the code hint says that the second param is "exported", so do the Document of @babel/types

So how can I send the param "exported" rightly?
Can you post an example of what you're trying to transform the code in source.index into? What is the finished result that you want to see?
Can you post an example of what you're trying to transform the code in source.index into? What is the finished result that you want to see?
Thanks for replying, I want to transform the js file from commonJS into ESmodule, here's the example:
import VirtualMachine1 from './virtual-machine';
export { VirtualMachine1 };

Once upon a time, I dreamt I was a butterfly, fluttering hither and thither, to all intents and purposes a butterfly. I was conscious only of my happiness as a butterfly, unaware that I was myself. Soon I awaked, and there I was, veritably myself again. Now I do not know whether I was then a man dreaming I was a butterfly, or whether I am now a butterfly, dreaming I am a man.
(c) Zhuangzi
@TrumanGao why don’t you just use 🐊Putout for this purpose?
Changing file extension to .mjs or adding type=module will be enough. If you want to transform code programmatically, use @putout/plugin-convert-commonjs-to-esm.
have a look at this discussion here: https://github.com/benjamn/ast-types/issues/425#issuecomment-1007846129 Someone found a way of making it