Skip to content

Commit

Permalink
add react fast refresh (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott authored and drwpow committed Jul 24, 2020
1 parent be7889d commit 62042ad
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 51 deletions.
27 changes: 27 additions & 0 deletions packages/create-snowpack-app/LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

This license applies to parts of packages/plugin-react-refresh/plugin.js originating
from the https://github.com/vitejs/vite-plugin-react repository:

"""
MIT License

Copyright (c) 2020-present, Yuxi (Evan) You

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,9 @@ if (isTS) {

module.exports = {
scripts,
plugins: ["@snowpack/plugin-babel", "@prefresh/snowpack"],
devOptions: {},
installOptions: {
installTypes: isTS,
},
plugins: [
"@snowpack/plugin-babel",
"@prefresh/snowpack"
]
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"presets": [["@babel/preset-react"], "@babel/preset-typescript"],
"plugins": ["@babel/plugin-syntax-import-meta"],
"env": {
"development": {
"plugins": ["react-refresh/babel"]
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const isTS = fs.existsSync(path.join(cwd, "tsconfig.json"));

const scripts = {
"mount:public": "mount public --to /",
"mount:web_modules": "mount web_modules",
"mount:src": "mount src --to /_dist_",
};

Expand All @@ -17,6 +16,7 @@ if (isTS) {

module.exports = {
scripts,
plugins: ["@snowpack/plugin-babel", "@snowpack/plugin-react-refresh"],
devOptions: {},
installOptions: {
installTypes: isTS,
Expand Down
3 changes: 0 additions & 3 deletions packages/create-snowpack-app/packages/plugin-babel/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ module.exports = function plugin(config, options) {
return {
defaultBuildScript: "build:js,jsx,ts,tsx",
async build({ contents, filePath, fileContents }) {
if (filePath.includes("web_modules")) {
return { result: contents };
}
const result = await babel.transformAsync(contents || fileContents, {
filename: filePath,
cwd: process.cwd(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "@snowpack/plugin-react-refresh",
"version": "0.6.2",
"main": "plugin.js",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"dependencies": {
"react-refresh": "^0.8.0"
},
"gitHead": "795f4311d79a70cc9f19f21b512b7f8675d73f17"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @snowpack/plugin-react-refresh (Fast Refresh)
* Based on details provided by:
* - https://github.com/facebook/react/issues/16604#issuecomment-528663101
* - https://github.com/vitejs/vite-plugin-react (see LICENSE)
*/

const fs = require("fs");

const reactRefreshLoc = require.resolve(
"react-refresh/cjs/react-refresh-runtime.development.js"
);
const reactRefreshCode = fs
.readFileSync(reactRefreshLoc, { encoding: "utf-8" })
.replace(`process.env.NODE_ENV`, JSON.stringify("development"));

function transformHtml(contents, urlPath) {
return contents.replace(
/<body.*?>/,
`$&
<script>
function debounce(e,t){let u;return()=>{clearTimeout(u),u=setTimeout(e,t)}}
const exports = {};
${reactRefreshCode}
exports.performReactRefresh = debounce(exports.performReactRefresh, 30);
window.$RefreshRuntime$ = exports;
window.$RefreshRuntime$.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
</script>`
);
}

function transformJs(contents, urlPath) {
return `
/** React Refresh: Setup **/
if (import.meta.hot) {
var prevRefreshReg = window.$RefreshReg$;
var prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = (type, id) => {
window.$RefreshRuntime$.register(type, ${JSON.stringify(
urlPath
)} + " " + id);
}
window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
${contents}
/** React Refresh: Connect **/
if (import.meta.hot) {
window.$RefreshReg$ = prevRefreshReg
window.$RefreshSig$ = prevRefreshSig
import.meta.hot.accept(() => {
window.$RefreshRuntime$.performReactRefresh()
});
}`;
}

module.exports = function reactRefreshTransform() {
return {
transform({ contents, urlPath, isDev }) {
if (!isDev) {
return null;
}
if (urlPath.endsWith(".js") && /\$RefreshReg\$\(/.test(contents)) {
return { result: transformJs(contents, urlPath) };
}
if (urlPath.endsWith("/") || urlPath.endsWith(".html")) {
return { result: transformHtml(contents, urlPath) };
}
},
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@snowpack/app-scripts-react/babel.config.json"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@snowpack/app-scripts-react/babel.config.json"
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import React from 'react';
import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
// TODO: Remove before merging, this was just for fast-refresh testing
const [counter, setCounter] = useState(5);
setTimeout(() => setCounter(counter + 1), 1000);
return (
<div className={'App'}>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.jsx</code> and save to reload.
{counter} Edit <code>src/App.jsx</code> and save to reload.
</p>
<a
className="App-link"
Expand Down
43 changes: 2 additions & 41 deletions packages/create-snowpack-app/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10917,7 +10917,7 @@ react-is@^16.12.0, react-is@^16.8.1, react-is@^16.8.4:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==

react-refresh@^0.8.2:
react-refresh@^0.8.0, react-refresh@^0.8.2:
version "0.8.2"
resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.8.2.tgz#24bb0858eac92b0d7b0dd561747f0c9fd6c60327"
integrity sha512-n8GXxo3DwM2KtFEL69DAVhGc4A1THn2qjmfvSo3nze0NLCoPbywazeJPqdp0RdSGLmyhQzeyA+XPXOobbYlkzg==
Expand Down Expand Up @@ -11808,46 +11808,7 @@ snapdragon@^0.8.1:
source-map-resolve "^0.5.0"
use "^3.1.0"

snowpack@^2.0.0-0:
version "2.0.0-rc.4"
resolved "https://registry.yarnpkg.com/snowpack/-/snowpack-2.0.0-rc.4.tgz#a316b62b33fbd5ed4354a56cf683e87cb1179c0f"
integrity sha512-Jub/3g/A2MEOJV8647ZsWgeudPhcYmoItmn8wKuvuVoYHn+0GtW+voCQVlE1SG8ROJYKt4ZbXhyraUrZi+BX+A==
dependencies:
"@babel/plugin-syntax-import-meta" "^7.8.3"
"@rollup/plugin-alias" "^3.0.1"
"@rollup/plugin-commonjs" "~11.0.0"
"@rollup/plugin-json" "^4.0.0"
"@rollup/plugin-node-resolve" "^7.1.0"
"@rollup/plugin-replace" "^2.1.0"
"@types/tar" "^4.0.3"
ansi-escapes "^4.3.1"
cacache "^15.0.0"
cachedir "^2.3.0"
chalk "^4.0.0"
chokidar "^3.4.0"
cosmiconfig "^6.0.0"
css-modules-loader-core "^1.1.0"
deepmerge "^4.2.2"
es-module-lexer "^0.3.17"
esbuild "^0.3.0"
etag "^1.8.1"
execa "^4.0.0"
glob "^7.1.4"
got "^11.1.4"
is-builtin-module "^3.0.0"
jsonschema "^1.2.5"
mime-types "^2.1.26"
mkdirp "^1.0.3"
ora "^4.0.4"
p-queue "^6.2.1"
resolve-from "^5.0.0"
rimraf "^3.0.0"
rollup "^2.3.0"
tar "^6.0.1"
validate-npm-package-name "^3.0.0"
yargs-parser "^18.1.3"

snowpack@^2.0.0-rc.4:
snowpack@^2.0.0-0, snowpack@^2.0.0-rc.4:
version "2.0.0-rc.4"
resolved "https://registry.yarnpkg.com/snowpack/-/snowpack-2.0.0-rc.4.tgz#a316b62b33fbd5ed4354a56cf683e87cb1179c0f"
integrity sha512-Jub/3g/A2MEOJV8647ZsWgeudPhcYmoItmn8wKuvuVoYHn+0GtW+voCQVlE1SG8ROJYKt4ZbXhyraUrZi+BX+A==
Expand Down

0 comments on commit 62042ad

Please sign in to comment.