Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to use hooks in compiled package #4330

Closed
1 task done
pm0u opened this issue Mar 28, 2024 · 0 comments
Closed
1 task done

Unable to use hooks in compiled package #4330

pm0u opened this issue Mar 28, 2024 · 0 comments

Comments

@pm0u
Copy link

pm0u commented Mar 28, 2024

  • Check if updating to the latest Preact version resolves the issue

Describe the bug
I have a package that is build using vite and the preact plugin. I created this via the vite CLI helper: npm create vite@latest --template preact-ts. I ripped out all the HTML related things since all I cared about was compiling the context and consumer, so this just spits out a JS file.

I have a simple provider and context consumer:

// provider and hook
import { useContext, createContext } from "react";

interface Context {
  test: string;
}
interface ContextProps {
  children: JSX.Element;
}

// @ts-expect-error
const Context = createContext<MapContext>({});

export const MyProvider = ({ children }: ContextProps) => {
  return (
    // @ts-expect-error errors bc react types mismatch preact
    <Context.Provider value={{ test: "test" }}>{children}</Context.Provider>
  );
};

export const useMyContext = () => {
  const context = useContext(Context);
  if (context === undefined) {
    throw new Error("useMyContext must be used in child of MyProvider!");
  }
  return context;
};
// consumer
import { useMyContext } from "./my-context";

export const MyConsumer = () => {
  const { test } = useMyContext();
  console.log({ test });
  return <div></div>;
};

I attempted to exclude all preact/react possible deps from bundling so as to prevent duplicates.
I wasn't sure if react or preact would be the ticket here with Vite's aliasing so I just threw in both on top of pulling peer deps from the package.json. Note this is vite.config.mts otherwise some dep of preact/preset-vite threw esmodule errors. I tried with both type: module and without in package.json, I removed it as I thought this could cause some bundling issue. Neither type module with a TS config or no type module with an mts config seems to work.

import { defineConfig } from "vite";
import { resolve } from "path";
import pkg from "./package.json";
import preact from "@preact/preset-vite";

const peerDependencies = Object.keys(pkg.peerDependencies);

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [preact()],
  build: {
    sourcemap: "inline",
    minify: false,
    lib: {
      entry: resolve(__dirname, "src/index.ts"),
      name: pkg.name,
      formats: ["es"],
      fileName: (format) => `index.${format}.js`,
    },
    rollupOptions: {
      external: [
        ...peerDependencies,
        "preact/compat",
        "preact/hooks",
        "react",
        "react-dom",
      ],
    },
  },
});

Both components are exported from the entry index

export * from './my-context'
export * from './my-consumer'
// package.json
{
  "name": "my-package",
  "version": "0.0.1",
  "private": true,
  "main": "dist/index.es.js",
  "module": "dist/index.es.js",
  "types": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "sideEffects": true,
  "scripts": {
    "clean": "rm -rf ./dist",
    "build": "npm run clean && vite build  && tsc --declaration --emitDeclarationOnly --project tsconfig.production.json"
  },
  "peerDependencies": {
    "preact": "^10.13.1"
  },
  "devDependencies": {
    "@preact/preset-vite": "^2.8.0",
    "eslint": "^8.57.0",
    "eslint-config-preact": "^1.3.0",
    "typescript": "^5.4.3"
  },
  "eslintConfig": {
    "extends": "preact"
  }
}

I then attempt to consume these in another project (currently via npm-link)
This was also created using npm create vite preact-ts.
Using the basic scaffolding with index.html

// src/index.tsx
import { render } from "preact";
import { MyProvider, MyConsumer } from "my-package";

export function App() {
  return (
    <MyProvider>
      <MyConsumer />
    </MyProvider>
  );
}

render(<App />, document.getElementById("app"));

vite.config.mts I've included sourcemaps and disabled minification top to bottom to try to aid in debugging.

import { defineConfig } from "vite";
import preact from "@preact/preset-vite";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [preact()],
  build: {
    minify: false,
    sourcemap: "inline",
  },
});

This works in a dev build. However when I npm run build && npm run preview I get the following error:

image

Expected behavior
This works in production as it does in development

@preactjs preactjs locked and limited conversation to collaborators Mar 28, 2024
@JoviDeCroock JoviDeCroock converted this issue into discussion #4331 Mar 28, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant