Giter Club home page Giter Club logo

vite-plugin-react-refresh's Introduction

[ARCHIVED] vite-plugin-react

This repo has moved to @vitejs/plugin-react-refresh.


Provides React Fast Refresh support for Vite 1.

This plugin is included by default in the create-vite-app React template.

// vite.config.js
module.exports = {
  jsx: 'react',
  plugins: [require('vite-plugin-react')]
}

vite-plugin-react-refresh's People

Contributors

aleclarson avatar csr632 avatar elmassimo avatar patak-dev avatar yyx990803 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-plugin-react-refresh's Issues

react启动失败

yarn create vite-app --template react
yarn
yarn dev
启动后随后就报错了~
image

Uncaught TypeError: Cannot read property 'forEach' of undefined
at Object.injectIntoGlobalHook (@react-refresh:467)
at (index):8

App.jsx:1 Uncaught Error: vite-plugin-react can't detect preamble.

第一次提,不专业~

浏览器提示 insert-css没有导出insertCss

描述:我使用的less,所以我先yarn add less less-loader -D,然后贴出我的vite.config.ts
`import * as reactPlugin from 'vite-plugin-react'
import type { UserConfig } from 'vite'

const config: UserConfig = {
jsx: 'react',
cssPreprocessOptions: {
less: {
modifyVars: {
}
}
},
plugins: [reactPlugin]
}

export default config
`
然后浏览器无法运行提示
image

os:win10
browser:chrome v85.0.4183.102

Support preact

Hi, is it possible to support preact by aliasing the react dependencies? Main problem is vite-plugin-react includes react's refresh and there's no way to configure it to use prefresh from preact. Would be good if it's possible to turn off or switch the refresh plugin.

Thanks.

Alternative to @pika/react

Hi, snowpack itself is no longer using @pika/react. It hasn't been updated - react 16.4 and 17 have both been released but @pika/react hasn't updated. Is there an alternate solution that the users can move to?

Thanks.

use react instead of @pika/react

#29 We can use React without esm bundle. In that case, rollup/commonjs will make React as a single default export.

Details: use react without this plugin

One line config, and install the latest react & react-dom. It could run!

// vite.config.ts
const config: UserConfig = { jsx: "react" };
export default config;
{ "dependencies": {
    "react": "^17.0.1",
    "react-dom": "^17.0.1" } }
// main.tsx
import React from "react";
import ReactDOM from "react-dom";
ReactDOM.render(<h1>Hello</h1>, document.getElementById("root"));

But there is no hot module reload. That's why react-refresh comes.

Problem is, since rollup only exports React, we can not do import { useState } from "react". You can checkout /@modules/react.js in [ DevTools > Sources > Page ] to verify that. I put it here:

export { r as default } from '/@modules/common/index-b0081338.js';
import React from "react";
function App() {
	const [name, setName] = React.useState(""); // ok
import React, { useState } from "react";
function App() {
	const [name, setName] = useState(""); // not ok

Solution is that, instead of using another package, we can modify /@modules/react.js to export everything we need. Along with this plugin's react-refresh part, you can try this vite.config.ts:

import type { UserConfig, Plugin, ServerPlugin, Transform } from "vite";
import originalReactPlugin from "vite-plugin-react";
import { readBody } from "vite";

declare module "vite-plugin-react" {
    export const configureServer: ServerPlugin;
    export const transforms: Transform[];
}

const createReactPlugin: () => Plugin = () => {
    // just ignore the pika resolver
    return {
        configureServer: originalReactPlugin.configureServer,
        transforms: originalReactPlugin.transforms,
    };
};

const config: UserConfig = {
    jsx: "react",
    plugins: [
        createReactPlugin(),
        {
            configureServer: ({ app }) => {
                app.use(async (ctx, next) => {
                    await next();
                    if (ctx.path === "/@modules/react.js") {
                        let js = (await readBody(ctx.body))!;
                        js = js.replace("export { r as default", "import { r as React");
                        js += `
const { useState, useEffect } = React;  // add more exports here
export { useState, useEffect };         // and here
export default React;`;
                        ctx.body = js;
                    }
                });
            },
        },
    ],
};

export default config;

I'm not sure whether rollup will build stable output like that. At least this solution LGTM.

Update: just make a script to gather exported names.

Refreshing Contexts Not Refreshing

I don't think this is a vite-plugin-react issue but I thought I would start here before filing an issue in react. I've searched through threads and issues but haven't found anything related to this in this repository or any other repository!

Problem

I'm using a Context and Provider throughout my app. When I saved the file that defines the provider, it is reloaded properly but the data is not provided to the useContext as expected. For example, I have the following very Provider:

export const UserContext = createContext({ name: undefined });

export const UserProvider = (props) => {
  const name = "Tester";
  return <UserContext.Provider value={{ name }}>{props.children}</UserContext.Provider>;
};

export const useUser = () => {
  return useContext(UserContext);
};

Then, in another file, I'm using the useContext hook:

import { useUser } from './auth'

function App() {
  const { name } = useUser();
  console.log('App.jsx')

  return (
    <div>{`My name is ${name}`}</div>
  )
}

Steps to Reproduce

git clone https://github.com/jsmith/fast-refresh-test
yarn # or npm i
yarn dev # or npm run dev

At this point, you'll see My name is Tester at http://localhost:3000. After saving auth.jsx, you'll see My name is undefined. If you open the console, you will see that the provider was actually reloaded but for some reason, the data wasn't actually sent to the context hook (ie. name was set to it's default value undefined).

Thanks so much 😃

React is not externaled when optimizing deps

image

Reproduce:

https://github.com/csr632/test-vite/tree/debug-plugin-react
After optimize, go to node_modules/.vite_opt_cache/styled-components, search for react.development.js in it. You can see react is bundled.

Investigate

When optimizing styled-components, react is resolved into @pika/react/source.development.js:
https://github.com/vitejs/vite-plugin-react/blob/a37f540ab16bfe256273b7719e9432a4b3b4efdf/src/resolver.ts#L7

but the rollup external config is @pika/react
image

Fix

vitejs/vite#218 and vitejs/vite-plugin-react#5 fix this.
I resolve the rollup external config with resolver before calling rollup to optimize. So that the rollup external config will be @pika/react/source.development.js instead of @pika/react.

"process is not defined" when using Workers

We inject the Vite global preamble in the main script on the window object.

But when importing workers during dev, they do not get the preamble as they have a different global context. Thus triggering

Uncaught ReferenceError: process is not defined.

The worker imports are processed by vite, for eg:

I see this on top of one of the imports:

import { createHotContext } from "/vite/hmr"; import.meta.hot = createHotContext("/@modules/monaco-editor/esm/vs/base/common/keyCodes.js");   import RefreshRuntime from "/@react-refresh";  let prevRefreshReg;  let prevRefreshSig;  if (!window.__vite_plugin_react_preamble_installed__) {    throw new Error(      "vite-plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201"    );  }  if (import.meta.hot) {    prevRefreshReg = window.$RefreshReg$;    prevRefreshSig = window.$RefreshSig$;    window.$RefreshReg$ = (type, id) => {      RefreshRuntime.register(type, "/Users/ashish.shubham/thoughtspot/node_modules/monaco-editor/esm/vs/base/common/keyCodes.js" + " " + id)    };    window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;  }/

Here window is not defined, since this is in the worker scope. We need to use self which still might not have $RefreshReg$ due to the difference in GlobalScope mentioned above.

Maybe we consider leaving Workers alone for HMR ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.