Using vite / rollup with npm workspaces, issue with react on production build

I am trying to create a local shared folder / workspace / package to share code between projects in a monorepo using npm workspaces, and it works in vite dev mode, but not when I build and preview using vite / rollup.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>TypeError: Cannot read properties of null (reading 'useState')
at react_production_min.useState (index.js:85289:286)
at useDebounceValue (index.js:86924:53)
at AppContainer (index.js:86942:36)
</code>
<code>TypeError: Cannot read properties of null (reading 'useState') at react_production_min.useState (index.js:85289:286) at useDebounceValue (index.js:86924:53) at AppContainer (index.js:86942:36) </code>
TypeError: Cannot read properties of null (reading 'useState')
    at react_production_min.useState (index.js:85289:286)
    at useDebounceValue (index.js:86924:53)
    at AppContainer (index.js:86942:36)

This is my folder structure:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>my-app/
├─ node_modules/
├─ packages/
│ ├─ shared/
│ ├─ app/
├─ package.json
</code>
<code>my-app/ ├─ node_modules/ ├─ packages/ │ ├─ shared/ │ ├─ app/ ├─ package.json </code>
my-app/
├─ node_modules/
├─ packages/
│  ├─ shared/
│  ├─ app/
├─ package.json

This is my root package.json:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"name": "frontends",
"version": "1.0.0",
"description": "Our frontends",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"workspaces": [
"packages/*"
],
"dependencies": {
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"autoprefixer": "10.4.17",
"postcss": "8.4.35",
"tailwindcss": "3.4.1"
}
}
</code>
<code>{ "name": "frontends", "version": "1.0.0", "description": "Our frontends", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "author": "", "license": "ISC", "workspaces": [ "packages/*" ], "dependencies": { "react": "18.2.0", "react-dom": "18.2.0" }, "devDependencies": { "autoprefixer": "10.4.17", "postcss": "8.4.35", "tailwindcss": "3.4.1" } } </code>
{
  "name": "frontends",
  "version": "1.0.0",
  "description": "Our frontends",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "workspaces": [
    "packages/*"
  ],
  "dependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "autoprefixer": "10.4.17",
    "postcss": "8.4.35",
    "tailwindcss": "3.4.1"
  }
}

This my shared package.json

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"name": "@myscope/shared",
"version": "1.0.0",
"description": "Shared components, libraries and utils for frontend projects",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"type": "module",
"author": "",
"license": "ISC",
"peerDependencies": {
"i18next": "23.11.3",
"oidc-client-ts": "2.4.0",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@testing-library/jest-dom": "6.4.2",
"@testing-library/react": "14.2.1",
"i18next": "23.11.3",
"oidc-client-ts": "2.4.0",
"react": "18.2.0",
"react-dom": "18.2.0"
}
}
</code>
<code>{ "name": "@myscope/shared", "version": "1.0.0", "description": "Shared components, libraries and utils for frontend projects", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "type": "module", "author": "", "license": "ISC", "peerDependencies": { "i18next": "23.11.3", "oidc-client-ts": "2.4.0", "react": "18.2.0", "react-dom": "18.2.0" }, "devDependencies": { "@testing-library/jest-dom": "6.4.2", "@testing-library/react": "14.2.1", "i18next": "23.11.3", "oidc-client-ts": "2.4.0", "react": "18.2.0", "react-dom": "18.2.0" } } </code>
{
  "name": "@myscope/shared",
  "version": "1.0.0",
  "description": "Shared components, libraries and utils for frontend projects",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "type": "module",
  "author": "",
  "license": "ISC",
  "peerDependencies": {
    "i18next": "23.11.3",
    "oidc-client-ts": "2.4.0",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "6.4.2",
    "@testing-library/react": "14.2.1",
    "i18next": "23.11.3",
    "oidc-client-ts": "2.4.0",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}

And I have a single React hook in shared:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React from "react";
/**
* Debounced value update, e.g. to trigger search after a user stops typing
* @param value
* @param delay
*/
export default function useDebounceValue(value: string, delay: number) {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = React.useState(value);
React.useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value]);
return debouncedValue;
}
</code>
<code>import React from "react"; /** * Debounced value update, e.g. to trigger search after a user stops typing * @param value * @param delay */ export default function useDebounceValue(value: string, delay: number) { // State and setters for debounced value const [debouncedValue, setDebouncedValue] = React.useState(value); React.useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value]); return debouncedValue; } </code>
import React from "react";

/**
 * Debounced value update, e.g. to trigger search after a user stops typing
 * @param value
 * @param delay
 */
export default function useDebounceValue(value: string, delay: number) {
  // State and setters for debounced value
  const [debouncedValue, setDebouncedValue] = React.useState(value);

  React.useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value]);

  return debouncedValue;
}

This is the app vite.config.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import { htmlInjectionPlugin } from "vite-plugin-html-injection";
// https://vitejs.dev/config/
export default defineConfig({
preview: {
port: 5174,
},
server: {
port: 5174,
},
plugins: [
react(),
htmlInjectionPlugin({
injections: [
{
name: "Global Config",
path: "./public/config.js",
type: "js",
injectTo: "head",
},
],
}),
],
build: {
assetsDir: "public/assets",
outDir: "./build",
minify: false,
target: "esnext",
assetsInlineLimit: 8192,
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
},
},
},
base: "./",
});
</code>
<code>import { defineConfig } from "vite"; import react from "@vitejs/plugin-react-swc"; import { htmlInjectionPlugin } from "vite-plugin-html-injection"; // https://vitejs.dev/config/ export default defineConfig({ preview: { port: 5174, }, server: { port: 5174, }, plugins: [ react(), htmlInjectionPlugin({ injections: [ { name: "Global Config", path: "./public/config.js", type: "js", injectTo: "head", }, ], }), ], build: { assetsDir: "public/assets", outDir: "./build", minify: false, target: "esnext", assetsInlineLimit: 8192, rollupOptions: { output: { entryFileNames: `assets/[name].js`, chunkFileNames: `assets/[name].js`, assetFileNames: `assets/[name].[ext]`, }, }, }, base: "./", }); </code>
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import { htmlInjectionPlugin } from "vite-plugin-html-injection";

// https://vitejs.dev/config/
export default defineConfig({
  preview: {
    port: 5174,
  },
  server: {
    port: 5174,
  },
  plugins: [
    react(),
    htmlInjectionPlugin({
      injections: [
        {
          name: "Global Config",
          path: "./public/config.js",
          type: "js",
          injectTo: "head",
        },
      ],
    }),
  ],
  build: {
    assetsDir: "public/assets",
    outDir: "./build",
    minify: false,
    target: "esnext",
    assetsInlineLimit: 8192,
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`,
      },
    },
  },
  base: "./",
});

And inside app I have an appContainer.tsx where I try to use useDebounceValue (as a test only)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { useEffect } from "react";
import { useSelector } from "react-redux";
import { useDebounceValue } from "@myscope/shared/react/hooks";
import { MenuItem } from "../core/models/menu";
import { RootState } from "../core/state/dependencies";
export const AppContainer = () => {
const activeMenu: MenuItem | null | undefined = useSelector(
(state: RootState) => state.menu.activeMenu,
);
const debouncedTest = useDebounceValue(activeMenu?.title, 500);
useEffect(() => {
console.info(debouncedTest);
}, [debouncedTest]);
return (
<div>Test</div>
);
};
</code>
<code>import { useEffect } from "react"; import { useSelector } from "react-redux"; import { useDebounceValue } from "@myscope/shared/react/hooks"; import { MenuItem } from "../core/models/menu"; import { RootState } from "../core/state/dependencies"; export const AppContainer = () => { const activeMenu: MenuItem | null | undefined = useSelector( (state: RootState) => state.menu.activeMenu, ); const debouncedTest = useDebounceValue(activeMenu?.title, 500); useEffect(() => { console.info(debouncedTest); }, [debouncedTest]); return ( <div>Test</div> ); }; </code>
import { useEffect } from "react";
import { useSelector } from "react-redux";
import { useDebounceValue } from "@myscope/shared/react/hooks";

import { MenuItem } from "../core/models/menu";
import { RootState } from "../core/state/dependencies";


export const AppContainer = () => {
  const activeMenu: MenuItem | null | undefined = useSelector(
    (state: RootState) => state.menu.activeMenu,
  );

  const debouncedTest = useDebounceValue(activeMenu?.title, 500);

  useEffect(() => {
    console.info(debouncedTest);
  }, [debouncedTest]);

  return (
    <div>Test</div>
  );
};

In vite dev this runs fine, but if I do vite build && vite preview, it fails with the null error from the top.

If I inspect the index.js that rollup builds, I see that all usage of react from the “app” uses the following react ref:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var reactExports$1 = react$1.exports;
const React$1 = /*@__PURE__*/getDefaultExportFromCjs(reactExports$1);
</code>
<code>var reactExports$1 = react$1.exports; const React$1 = /*@__PURE__*/getDefaultExportFromCjs(reactExports$1); </code>
var reactExports$1 = react$1.exports;
const React$1 = /*@__PURE__*/getDefaultExportFromCjs(reactExports$1);

But the one from useDebounceValue seem to have it’s own react reference which ends up being null.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var reactExports = react.exports;
const React = /*@__PURE__*/getDefaultExportFromCjs(reactExports);
/**
* @license React
...
function useDebounceValue(value, delay) {
const [debouncedValue, setDebouncedValue] = React.useState(value);
React.useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value]);
return debouncedValue;
}
</code>
<code>var reactExports = react.exports; const React = /*@__PURE__*/getDefaultExportFromCjs(reactExports); /** * @license React ... function useDebounceValue(value, delay) { const [debouncedValue, setDebouncedValue] = React.useState(value); React.useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value]); return debouncedValue; } </code>
var reactExports = react.exports;
const React = /*@__PURE__*/getDefaultExportFromCjs(reactExports);

/**
 * @license React
...

function useDebounceValue(value, delay) {
  const [debouncedValue, setDebouncedValue] = React.useState(value);
  React.useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    return () => {
      clearTimeout(handler);
    };
  }, [value]);
  return debouncedValue;
}

What am I doing wrong here?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật