diff --git a/src/index.ts b/src/index.ts index 5d2d484..b92bcb2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,7 @@ import { addNamed as addNamedImport } from '@babel/helper-module-imports'; import { arrayExpression, callExpression, - exportDefaultSpecifier, + exportNamedDeclaration, ClassDeclaration, classExpression, ExportNamedDeclaration, @@ -192,6 +192,52 @@ function transformImportExportDefault(paths: NodePath[]) { } } +/** + * transforms `export { getServerSideProps }` import & export line + */ +function transformDatafetcherNamedImportExports( + paths: NodePath[], + dataFetcherName: 'getServerSideProps' | 'getStaticProps' +) { + for (const path of paths) { + if (isExportNamedDeclaration(path)) { + for (const specifier of path.node.specifiers) { + if (specifier.local.name === dataFetcherName) { + paths.forEach((path) => + path.traverse({ + ImportSpecifier(specifier) { + if (specifier.node.imported.name === dataFetcherName) { + specifier.node.local.name = `_${dataFetcherName}`; + } + }, + }) + ); + + path.insertAfter( + exportNamedDeclaration( + variableDeclaration('const', [ + variableDeclarator( + identifier(dataFetcherName), + identifier(`_${dataFetcherName}`) + ), + ]) + ) as any + ); + + path.node.specifiers.splice( + path.node.specifiers.indexOf(specifier), + 1 + ); + + if (path.node.specifiers.length === 0) { + path.remove(); + } + } + } + } + } +} + function shouldBeSkipped(filePath: string) { if (!filePath.includes('pages' + nodePath.sep)) { return true; @@ -219,6 +265,8 @@ function superJsonWithNext(): PluginObj { } transformImportExportDefault(path.get('body')); + transformDatafetcherNamedImportExports(path.get('body'), 'getServerSideProps'); + transformDatafetcherNamedImportExports(path.get('body'), 'getStaticProps'); const body = path.get('body'); diff --git a/test/pages/export gssP and page from other (repro #134)/output.js b/test/pages/export gssP and page from other (repro #134)/output.js index 2e58854..80cc353 100644 --- a/test/pages/export gssP and page from other (repro #134)/output.js +++ b/test/pages/export gssP and page from other (repro #134)/output.js @@ -1,10 +1,10 @@ import { withSuperJSONPage as _withSuperJSONPage } from 'babel-plugin-superjson-next/tools'; import { withSuperJSONProps as _withSuperJSONProps } from 'babel-plugin-superjson-next/tools'; import { - getServerSideProps, + getServerSideProps as _getServerSideProps, PreviewPage, } from '../../../common-components/contentful-elements/pages/preview'; - -export { getServerSideProps }; - +export const getServerSideProps = _withSuperJSONProps(_getServerSideProps, [ + 'smth', +]); export default _withSuperJSONPage(PreviewPage);