Skip to content
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

fix: add new build for styleless #798

Merged
merged 8 commits into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,6 @@ dist

# Mac
.DS_Store

# Vscode
.vscode
2 changes: 1 addition & 1 deletion examples/nextjs/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"moduleResolution": "node16",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
Expand Down
14 changes: 14 additions & 0 deletions examples/vite-react/App.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Sandpack } from "@codesandbox/sandpack-react";

const App = () => {
return (
<div>
<Sandpack />
<Sandpack theme="dark" />
<Sandpack template="nextjs" />
<Sandpack options={{ readOnly: true }} />
</div>
);
};

export default App;
12 changes: 12 additions & 0 deletions examples/vite-react/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/index.jsx"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions examples/vite-react/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<App />
</StrictMode>
);
16 changes: 16 additions & 0 deletions examples/vite-react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "3.1.0",
"vite": "4.0.0",
"esbuild-wasm": "0.15.12"
}
}
7 changes: 7 additions & 0 deletions examples/vite-react/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});
27 changes: 19 additions & 8 deletions sandpack-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,27 @@
},
"license": "Apache-2.0",
"author": "CodeSandbox",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"types": "dist/types/index.d.ts",
"sideEffects": [
"dist/index.css"
],
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
"./unstyled": {
"types": "./dist/unstyled/index.d.ts",
"import": "./dist/unstyled/index.esm.js",
"require": "./dist/unstyled/index.js"
},
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.js"
}
},
"scripts": {
"clean": "rm -rf dist",
"prebuild": "yarn run clean",
"test": "TEST_ENV=true jest . --transformIgnorePatterns \"node_modules/(?!@codemirror)/\" --modulePathIgnorePatterns \"e2e\"",
"lint": "eslint '**/*.ts?(x)' --fix",
"build": "rollup -c && yarn build:types",
"build:types": "tsc -p tsconfig.json",
"build": "rollup -c",
"build:publish": "yarn build",
"start": "tsc -p tsconfig.esm.json --watch",
"dev": "start-storybook -p 6006 --quiet",
Expand Down Expand Up @@ -69,7 +77,10 @@
"@types/lz-string": "^1.3.34",
"@types/node": "^9.4.6",
"@types/react": "^18.0.15",
"acorn-walk": "^8.2.0",
"astring": "^1.8.4",
"babel-loader": "^7.1.5",
"rollup-plugin-filesize": "^10.0.0",
"typescript": "4.4.4"
},
"peerDependencies": {
Expand Down
117 changes: 85 additions & 32 deletions sandpack-react/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,94 @@
const commonjs = require("@rollup/plugin-commonjs");
const replace = require("@rollup/plugin-replace");
const typescript = require("@rollup/plugin-typescript");
const filesize = require("rollup-plugin-filesize");

const pkg = require("./package.json");
const removeCss = require("./scripts/rollup-remove-css-transformer");

const configBase = {
input: "src/index.ts",
output: [
{
file: pkg.main,
exports: "named",
format: "cjs",
inlineDynamicImports: true,
interop: "auto",
},
{
file: pkg.module,
exports: "named",
format: "es",
inlineDynamicImports: true,
},
],
const basePlugins = [commonjs({ requireReturnsDefault: "preferred" })];

const external = [
"react/jsx-runtime",
...Object.keys(pkg.dependencies),
...Object.keys(pkg.devDependencies),
...Object.keys(pkg.peerDependencies),
];

plugins: [
typescript({ tsconfig: "./tsconfig.json" }),
replace({
preventAssignment: true,
values: { "process.env.TEST_ENV": "false" },
}),
commonjs({ requireReturnsDefault: "preferred" }),
],
external: [
"react/jsx-runtime",
...Object.keys(pkg.dependencies),
...Object.keys(pkg.devDependencies),
...Object.keys(pkg.peerDependencies),
],
};
const baseConfig = { input: "src/index.ts", external };

const configBase = [
{
...baseConfig,
plugins: basePlugins.concat(
replace({
preventAssignment: true,
values: {
"process.env.TEST_ENV": "false",
"process.env.SANDPACK_UNSTYLED_COMPONENTS": `"false"`,
},
}),
typescript({ tsconfig: "./tsconfig.json" }),
filesize()
),
output: [
{
dir: "dist",
exports: "named",
format: "cjs",
inlineDynamicImports: true,
interop: "auto",
},
{
dir: "dist",
chunkFileNames: "[name]-[hash].esm.js",
entryFileNames: "[name].esm.js",
exports: "named",
format: "es",
inlineDynamicImports: true,
},
],
},

{
...baseConfig,
treeshake: {
preset: "smallest",
manualPureFunctions: ["createStitches"],
},
plugins: basePlugins.concat(
replace({
preventAssignment: true,
values: {
"process.env.TEST_ENV": "false",
"process.env.SANDPACK_UNSTYLED_COMPONENTS": `"true"`,
},
}),
typescript({
tsconfig: "./tsconfig.json",
compilerOptions: { outDir: "dist/unstyled/" },
}),
removeCss(),
filesize()
),
output: [
{
dir: "dist/unstyled",
exports: "named",
format: "cjs",
inlineDynamicImports: true,
interop: "auto",
},
{
dir: "dist/unstyled",
chunkFileNames: "[name]-[hash].esm.js",
entryFileNames: "[name].esm.js",
exports: "named",
format: "es",
inlineDynamicImports: true,
},
],
},
];

module.exports = configBase;
51 changes: 51 additions & 0 deletions sandpack-react/scripts/rollup-remove-css-transformer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require("path");

const walk = require("acorn-walk");
const { generate } = require("astring");

module.exports = function () {
return {
name: "remove-css",
transform(code, id) {
const ast = this.parse(code);

const idArr = id.split("/");
idArr.pop();

const sourceDirPath = idArr.join("/");

let isCssImported = false;

walk.simple(ast, {
ImportDeclaration: (_node) => {
if (
path.resolve(sourceDirPath, _node.source.value) ===
path.join(__dirname, "../src/styles")
) {
const specify = _node.specifiers?.find(
(specify) => specify.imported.name === "css"
);

if (specify) {
isCssImported = true;
specify.imported.name = "fakeCss";
specify.local.name = "fakeCss";
}
}
},
CallExpression: (_node) => {
if (_node.callee.name === "css" && isCssImported) {
_node.type = "Identifier";
_node.name = "fakeCss";
delete _node.arguments;
}
},
});

return {
code: generate(ast),
};
},
};
};
21 changes: 11 additions & 10 deletions sandpack-react/src/styles/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,11 @@ import { createStitchesMock } from "./stitches-mock";
*/
export const THEME_PREFIX = "sp";

const getNodeProcess = (): false | string | undefined => {
if (typeof process === "undefined") return false;

return (
process.env.SANDPACK_BARE_COMPONENTS ||
process.env.NEXT_PUBLIC_SANDPACK_BARE_COMPONENTS
);
};

/**
* @category Theme
*/
export const { createTheme, css, getCssText, keyframes } = getNodeProcess()
// prettier-ignore
export const { createTheme, css, getCssText, keyframes } = process.env.SANDPACK_UNSTYLED_COMPONENTS === 'true'
? createStitchesMock
: createStitches({
prefix: THEME_PREFIX,
Expand Down Expand Up @@ -147,3 +139,12 @@ const simpleHashFunction = (str: string): number => {
}
return Math.abs(hash);
};

/**
* The fake `css` function used to match the real `css` function usage
* We use this for the unstyled bundle which do not need real class names
* `css` is a factory which return a className generator, but also it be used in scenarios which `toString` will be invoked
* so we also need to add the `toString` method to it.
*/
export const fakeCss = () => "";
fakeCss.toString = fakeCss;
2 changes: 1 addition & 1 deletion sandpack-react/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"emitDecoratorMetadata": true,
"noImplicitAny": true,
"jsx": "react-jsx",
"outDir": "dist/types",
"outDir": "dist",
"skipLibCheck": true
},
"include": ["src"],
Expand Down
14 changes: 11 additions & 3 deletions website/docs/src/pages/getting-started/layout.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,19 @@ For this, sandpack uses a small package called [`classer`](https://github.com/co
This pattern is compatible with most modern styling systems, including Tailwind, styled-components and emotion.
</Callout>

### Bare components and remove runtime styling
### Bare components, remove runtime styling or use unstyled components

`@codesanbdox/sandpack-react` relies on [@stitches/core](https://github.com/stitchesjs/stitches) to style its component, which is almost zero-runtime CSS-in-JS framework. However, if you want to get rid of any runtime script or create your own style on top of Sandpack components, we provide a way to return bare components, which will eliminate all Sandpack CSS style.
`@codesanbdox/sandpack-react` relies on [@stitches/core](https://github.com/stitchesjs/stitches) to style its component, which is almost zero-runtime CSS-in-JS framework. However, if you want to get rid of any runtime script or create your own style on top of Sandpack components, we provide a way to return unstyled components, which will eliminate all Sandpack CSS style.

To do it, you need to pass `SANDPACK_BARE_COMPONENTS` environment variable (`NEXT_PUBLIC_SANDPACK_BARE_COMPONENTS` for Nextjs) as `true`, which will remove the Stitches dependency, its execution and return only the HTML of the components.
To do it, you need to consume the same components from the `unstyled` subfolder, which doesn't contain the Stitches dependency. For example:

```jsx
import { Sandpack } from "@codesandbox/sandpack-react/unstyled";

const App = () => {
return <Sandpack />
};
```

## Themes

Expand Down
Loading