Exported TypeScript namespaces don’t compile properly with new SWC compiler
See original GitHub issueWhat version of Next.js are you using?
12.0.0
What version of Node.js are you using?
16.6.2
What browser are you using?
N/A
What operating system are you using?
macOS
How are you deploying your application?
N/A
Describe the Bug
In our Next.js 11 sites we use exported TypeScript namespaces for some shared package and style modules. It’s maybe ill-advised to use namespaces like this but it lets us write code like this:
namespace appValues {
const firstName = "Foo";
const lastName = "Bar";
export const fullName = `${firstName} ${lastName}`
}
export default appValues;
Which is roughly equivalent to this:
const firstName = "Foo";
const lastName = "Bar";
const appValues = {
fullName: `${firstName} ${lastName}`
}
export default appValues;
Unfortunately this isn’t working in Next.js 12 when SWC is used, presumably because SWC compiles this namespace code (AFAIK) incorrectly.
Expected Behavior
If appValues
is imported in another file this code should log “Foo Bar”:
import appValues from 'appValues'
console.log(appValues.fullName)
This would work in Next.js 11, but fails in Next.js 12 with Cannot read property 'fullName' of undefined
.
To Reproduce
Here’s a reproduction based on the latest create-next-app
(with the typescript
preset):
https://github.com/GrantASL19/nextjs-12-typescript-namespace-default-export-error
Note that VS Code doesn’t flag any type errors, but the build fails.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5
I have the same problem on my project after updating to Next.js 12.
If I try to use it somewhere else:
TypeError: Cannot read properties of undefined (reading 'getFormattedDate')
I noticed, if I save the namespace to a variable first, then it works:
Nonetheless, I should be able to export the namespace without saving it to a variable first.
I updated my reproduction again.
In case anyone else is blocked by this, I also found a simpler fix, which I’ve included in a comment in my repo. I hope this also helps debug the issue in SWC/Next.js.
If this module is exported from another module it will be
undefined
:Whereas this will work as expected (replaced
export default appValues;
withexport default (appValues);
: