diff --git a/examples/basic/src/routes/home/layout.tsx b/examples/basic/src/routes/home/layout.tsx
index 90b665dbf..37f03cfa1 100644
--- a/examples/basic/src/routes/home/layout.tsx
+++ b/examples/basic/src/routes/home/layout.tsx
@@ -2,6 +2,12 @@ import React from 'react';
import { RouterView } from '@shuvi/runtime';
export default function Layout() {
+ React.useEffect(() => {
+ if (typeof window !== 'undefined') {
+ console.log(`[useEffect] layout useEffect`);
+ }
+ }, []);
+
return (
{
consoleLog(`Hello from package-esmodule ${data}`);
+
+ if (typeof window !== 'undefined') {
+ consoleLog('[package-esmodule] Running in the browser');
+ }
};
diff --git a/packages/toolpack/src/webpack/config/browser.ts b/packages/toolpack/src/webpack/config/browser.ts
index a10f476d4..6a7070bb2 100644
--- a/packages/toolpack/src/webpack/config/browser.ts
+++ b/packages/toolpack/src/webpack/config/browser.ts
@@ -220,6 +220,10 @@ export function createBrowserWebpackChain(options: BaseOptions): WebpackChain {
{
...options,
__BROWSER__: true,
+ /**
+ * swc.optimizer can't handle `typeof window` correctly for dependencies
+ */
+ 'typeof window': JSON.stringify('object'),
// prevent errof of destructing process.env
'process.env': JSON.stringify('{}')
}
diff --git a/packages/toolpack/src/webpack/config/node.ts b/packages/toolpack/src/webpack/config/node.ts
index 7d83b6139..e08f6f979 100644
--- a/packages/toolpack/src/webpack/config/node.ts
+++ b/packages/toolpack/src/webpack/config/node.ts
@@ -48,7 +48,11 @@ export function createNodeWebpackChain(options: BaseOptions): WebpackChain {
chain.plugin('define').tap(([options]) => [
{
...options,
- __BROWSER__: false
+ __BROWSER__: false,
+ /**
+ * swc.optimizer can't handle `typeof window` correctly for dependencies
+ */
+ 'typeof window': JSON.stringify('undefined')
}
]);
diff --git a/test/e2e/shuvi-cli.test.ts b/test/e2e/shuvi-cli.test.ts
index 854f569ce..c914fd9f9 100644
--- a/test/e2e/shuvi-cli.test.ts
+++ b/test/e2e/shuvi-cli.test.ts
@@ -117,7 +117,11 @@ describe('shuvi/inspect', () => {
const project = createTestCtx('shuvi-cli');
const { message } = await project.run('inspect', ['--verbose']);
expect(message).toMatch(
- `definitions: { 'process.env.NODE_ENV': '"development"'`
+ `definitions: {
+ 'process.env.NODE_ENV': '\"development\"',
+ __BROWSER__: false,
+ 'typeof window': '\"undefined\"'
+ }`
);
const project2 = createTestCtx('shuvi-cli');
@@ -126,7 +130,11 @@ describe('shuvi/inspect', () => {
'--verbose'
]);
expect(message2).toMatch(
- `definitions: { 'process.env.NODE_ENV': '"production"'`
+ `definitions: {
+ 'process.env.NODE_ENV': '\"production\"',
+ __BROWSER__: false,
+ 'typeof window': '\"undefined\"'
+ }`
);
});
});