vitejs / vite-plugin-react-refresh Goto Github PK
View Code? Open in Web Editor NEWReact Fast Refresh plugin for Vite
License: MIT License
React Fast Refresh plugin for Vite
License: MIT License
Should we archive this repo and mark it as deprecated in favor of @vitejs/plugin-react-refresh?
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 ?
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.
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
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
.
Example:
import { ReactComponent as Logo } from './logo.svg';
function App() {
return (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
}
Reference: https://create-react-app.dev/docs/adding-images-fonts-and-files/#adding-svgs
@react-refresh:16 Uncaught ReferenceError: process is not defined
at @react-refresh:16
reproduce:
https://github.com/csr632/test-vite/tree/plugin-react
The injection of window.process happens after importing '/@react-refresh'
https://github.com/vitejs/vite-plugin-react/blob/0dedc26c5cc3890524e3e9cb8a7d4f84297a3e1e/src/serverPlugin.ts#L49
So plugins that append module code into html should resolve process.env.NODE_ENV
by themself.
描述:我使用的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
`
然后浏览器无法运行提示
os:win10
browser:chrome v85.0.4183.102
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.
#29 We can use React without esm bundle. In that case, rollup/commonjs will make React
as a single default export.
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.
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!
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>
)
}
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 😃
Internal server error: Failed to resolve import "/@react-refresh". Does the file exist?
I can try and attach a reproducible example, but it's on a fairly large project and will take me some time to whittle it down to get this error - I can't reproduce it on a fresh project.
Before I do - any ideas of why this might be occurring?
Uncaught SyntaxError: The requested module '/@modules/prop-types/index.js' does not provide an export named 'default'
Users are foreced to put "@pika/react" in their dependencies. Although this is reasonable for app development, it is not suitable for library development.
If user put @pika/react in devDependencies
, the optimize step will bundle react into optimized bundle, which leads to duplicate react error in dev. Reproduce: https://github.com/csr632/test-vite/tree/pika-react-dev-dep
Will I face major problems if I remove @pika/react and @pika/react-dom and replace them with native react and react-dom?
If you prefer commonjs, you can use export = config
. But I think export default config
is better if we can support vite.config.mjs
for users.
Or we can use export const reactPlugin = {}
and use const {reactPlugin} = require('vite-plugin-react')
in commonjs and use import {reactPlugin} from 'vite-plugin-react'
in esm.
1
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.