Managing Javascript, stylesheets, and other assets in the pipeline can be a difficult task. We have problems like: How do we get rid of the React runtime in the bundle? How do we optimize our CSS files? And how do we deal with the static files?
This is a continuation of the first part of "Building Static Sites without React - Using React" so please make sure to read the first part before moving on.
// src/useScripts.js
import { useEffect } from "react";
export function useScripts(scriptLoaders) {
useEffect(() => {
loadScripts(scriptLoaders);
});
}
// Each dynamic import is asynchronous
async function loadScripts(scriptLoaders) {
for (const load of scriptLoaders) {
await load();
}
}
npx -p @storybook/cli sb init
// stories/pages.stories.js
import React from "react";
import Home from "../pages/Home";
import AboutUs from "../pages/AboutUs";
export default { title: "Pages" };
export { Home, AboutUs };
├── pages │ ├── AboutUs.jsx │ └── Home.jsx ├── scripts │ └── build.js ├── src │ └── useScripts.js ├── stories │ └── pages.stories.js ├── babel.config.js ├── package.json └── webpack.config.js
yarn storybook
// home.js
console.log("home.js");
const title = document.getElementById("home");
let cyan = true;
title.style.transition = "color 0.5s";
setInterval(() => {
title.style.color = cyan ? "cyan" : "black";
cyan = !cyan;
}, 1000);
//about-us.js
console.log("about-us.js");
//Home.jsx
import React from "react";
import { useScripts } from "../src/useScripts";
const Home = () => {
useScripts([() => import("../src/home")]);
return <h1 id="home">Home Page</h1>;
};
export default Home;
import React from "react";
import { useScripts } from "../src/useScripts";
const AboutUs = () => {
useScripts([() => import("../src/about-us")]);
return <h1>About Us</h1>;
};
export default AboutUs;
// Home.css
#home {
transition: color 0.2s;
}
// Home.jsx
import React from "react";
import { useScripts } from "../src/useScripts";
import "./Home.css"; // import stylesheets
const Home = () => {
useScripts([() => import("../src/home")]);
return <h1 id="home">Home Page</h1>;
};
export default Home;
// home.js
console.log("home.js");
const title = document.getElementById("home");
let cyan = true;
// title.style.transition = "color 0.5s"; <-- remove this
setInterval(() => {
title.style.color = cyan ? "cyan" : "black";
cyan = !cyan;
}, 1000);
From us to your inbox weekly.