Code Monkey home page Code Monkey logo

vite-plugin-react-pages's Introduction

📘 vite-plugin-react-pages

npm package

vite-plugin-react-pages (vite-pages) is a React app framework powered by vite. It is very suitable for:

  • blog site
  • documentation site for your library or product
  • stories/demos/playgrounds for your React components or libraries (like storybook.js)

It provides many features that help developers build a React App quickly:

  • Fantastic development experience. Start the local development server in a blink, even when you have many pages. Hot module replacement works with React and Mdx, so you can get instant feedback when you edit your code.
  • Filesystem based routing. By following a simple filesystem routing convention, It is easy to create, locate and develop pages. You don't need to worry about routing configuration. For advanced users, you can tell vite-pages how to find page files, so that vite-pages can work with any project file structure.
  • Support Mdx. You can write content with either "normal React" or Mdx. Normal Reactjs is more flexible and composable. While Mdx is more readable and easier to edit. You can choose the proper format for your task. These formats can import each other like normal esModules.
  • Powerful theme customization. Vite-pages itself doesn't render any concrete DOM node. You can customize anything on the page with theme. It is easy to write a theme that is sharable and configurable. If you use typescript, the users of your theme will get type-check and intelliSense.
  • Automatic code splitting based on pages. Visitors don't need to download the whole app, they only load page data as needed.
  • Support static site generation out of the box. By pre-rendering your app into HTML at buildtime, users can see the content before any JS is loaded. With this feature, you can deploy your single page apps on GitHub Pages(which doesn't natively support single page apps).
  • Tools for Library documentation. Vite-pages provides some tools to reduce the maintenance costs for library authors and make their documents more easily to read.

Translation of this README

Getting stated

Try it online on StackBlitz

You can play with these demo projects in your browser, without installing anything on your machine.

Initialize a demo project locally

  1. Initialize a vite-pages project (with npm 7+):
    • execute npm init vite-pages app-demo -- --template app to initialize an app project, or
    • execute npm init vite-pages library-demo -- --template lib to initialize a library project, or
    • execute npm init vite-pages library-monorepo-demo -- --template lib-monorepo to initialize a library project with monorepo setup.
    • If you are using npm 6.x, the extra double-dash before --template should be deleted. For example, npm init vite-pages app-demo --template app.
  2. npm install
  3. npm run dev and play with the local dev environment.
  4. npm run build.
  5. npm run ssr. You can disable javascript in your browser, to verify if it can still render.

Read the documentation

Read the documentation of vite-plugin-react-pages.

vite-plugin-react-pages's People

Contributors

aleclarson avatar bluwy avatar caesar-nobug avatar cijiugechu avatar codpoe avatar csr632 avatar infomiho avatar itkrt2y avatar sapphi-red avatar sauntimo avatar xiaoxiangmoe avatar yang1206 avatar zheeeng 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

vite-plugin-react-pages's Issues

How to run packaged file in local,such as open in browser “file:///xxxxx/library-demo/public/index.html”

I want to deploy the docs to the GitLab Page。I found that the files in dir: public could not be opened statically.
These are my steps:
1、npm init vite-pages library-demo --template lib

2、vite output dir: 'public' (Let the output directory be 'public ')

3、 npm run build:page

 "scripts": {
    "build:page": "rm -rf public && vite build --config ./vite.config.ts",
  },

4、select the file:'public/index.html' to run in the browser

Can you give me some advice? thx.

TsInfo improvements

Consider the following case:

type Variant = "primary" | "secondary";

type Size = "sm" | "md" | "lg";

type Dimension = {
  w?: number;
  h?: number;
}

interface AsProp {
  as?: any;
}

interface BaseProps {
  size?: Size;
  wh?: Dimension;
}

interface ButtonProps extends BaseProps, AsProp {
  variant?: Variant | "link";
}

The TsInfo should show following output:

Name Description Type Default Value
variant "primary" | "secondary" | "link"
size "sm" | "md" | "lg"
wh { w: number, h: number }
as any

What I am getting:

Name Description Type Default Value
variant Variant | "link"

Suggested improvements:

  1. expand type references
  2. expand heritage clauses
  3. allow to skip certain heritage types

Examples:

  1. <TsInfo src="./Button.tsx" name="ButtonProps"/> should expand ButtonProps only no heritage types
  2. ` should expand inherited props too
  3. <TsInfo src="./Button.tsx" name="ButtonProps" heritage="AsProp"/> should expand inherited props from AsProp and not all (can be comma separated names).

And the jsx api should be like:

import _TsInfo0 from './types.ts?tsInfo=ButtonProps'

import _TsInfo0 from './types.ts?tsInfo=ButtonProps&heritage=true'

import _TsInfo0 from './types.ts?tsInfo=ButtonProps&heritage=AsProp'

antd Card bug

loading状态dev时候可以,打包后显示不出来。
骨架屏组件自身的loading 没问题

How to enable url hash mode?

Hello!

First, BIG THANKS for all your hard work on this great project! I think it deserves applause for a competitive solution in the React world!

Just caught it up in the previous version of the doc-site code that a useHashRouter: true is exposed in the vite-plugin-react-pages configs, like:

// vite.config.ts, modified from "basic" demo.

import { defineConfig } from 'vite'
import * as path from 'path'
import reactRefresh from '@vitejs/plugin-react-refresh'
import mdx from 'vite-plugin-mdx'
import pages from 'vite-plugin-react-pages'

module.exports = defineConfig({
  plugins: [
    reactRefresh(),
    mdx(),
    pages({
      useHashRouter: true, // <--- here it is
      pagesDir: path.join(__dirname, 'pages'),
    }),
  ],
})

Question:

  1. Is it ready to use?
  2. If so, will it affect the pageStrategy?

(I've found that when changed, my inter-links within markdown files will have to use something like [another-page](#/another-page) with a # in there.)

Plans for `vite-plugin-mdx`

Hi @csr632,

What are your plans with vite-plugin-mdx? I'm the author of https://github.com/brillout/vite-plugin-mdx.

For the sake of Vite's ecosystem, it would be nice to have only one vite-plugin-mdx.

I don't mind giving my version away to someone willing to maintain a plugin that is view framework agnostic, i.e. that works with React, Vue, Preact, etc.

Initialization of a vite-pages doesn't work

Hi,

this command doesn't work for me:

npm init @csr632/vite-app my-app --template react-pages-app

It shows this error:
image

I don't understand so much to the npm-init command but it's probably caused by the linking to the main repo with create-vite-app, isn't it?

Can `__index` be changed to another name?

Why does this name need to start with an underscore? By default, github pages ignores such files, making it necessary to add an .nojekyll. So I think this should be changed to another name?

[Need help] How to add images?

Hello!

Firstly, BIG THANKS to all of you working on this great project, which is very promising in combination with vite + react setup. I'm actually integrating this as my doc site. I followed the advanced FS routing to apply my own pageStrategy. Now I want to add images to my markdown files.

Suppose my project structure is (I tried to simplify):

- docs/
|-- _theme.tsx
|-- index.html
|-- README.md <-- this page requires the diagram.png
|               .. something like ![my-diagram](./static/images/diagram.png)
`-- static
    `-- images
        `-- diagram.png
- output/
`-- docs/   <-- this is the expected outDir
- package.json
- tsconfig.json
- vite.config.ts

and my vite.config.ts is like:

import { defineConfig } from 'vite';
import { resolve } from 'path';
import react from '@vitejs/plugin-react';
import mdx from 'vite-plugin-mdx';
import pages, {
  PageStrategy,
  FileHandler,
  extractStaticData,
} from 'vite-plugin-react-pages';

export default defineConfig({
  plugins: [
    react(), // this is my adoption, hopefully not related to this question
    mdx(),
    pages({
      pagesDir: resolve(__dirname, 'docs'),
      pageStrategy: new PageStrategy(function findPages(pagesDir, helpers) {
        helpers.watchFiles(
          pagesDir,
          '**/*.md',
          fileHandler
        );
      })
    }),
  ],
  root: 'docs',
  base: '/help/',  // to be served from 'http://my-server/help/'
  build: {
    outDir: '../output/docs',
    emptyOutDir: true
  }
});

const fileHandler: FileHandler = async (file, fileHandlerAPI) => {
  const pagePublicPath = getPagePublicPath(file.relative);
  fileHandlerAPI.addPageData({
    pageId: pagePublicPath,
    dataPath: file.path,
    staticData: await extractStaticData(file),
  });
};

/**
 * turn `sub-path/page2/welcome.md` into `/sub-path/page2/welcome`,
 * and `sub-path/page2/README.md` into `/sub-path/page2`
 */
function getPagePublicPath(relativePageFilePath: string) {
  let pagePublicPath = relativePageFilePath.replace(
    /(README)?\.md$/,
    ''
  );
  // remove ending slash
  pagePublicPath = pagePublicPath.replace(/\/$/, '');
  // add starting slash
  pagePublicPath = `/${pagePublicPath}`;
  console.log(`find new page: [${relativePageFilePath}] -> ${pagePublicPath}`);
  return pagePublicPath;
}

and I use vite build to build the docs. What I found is there's no images inside output/docs.

Question:

  1. How to config so that I can see images copied to the outDir?
  2. Is the path to the image (![my-diagram](./static/images/diagram.png)) in correct format?

Alpha release

Description

In the current alpha release , vite v4 alpha and rollup v3 are not specified as dependencies ( still v3 and v2 instead ) , and then version conflict is caused ( related PR ).

Should vite-pages's alpha release be in sync with vite ? Maybe vite-ecosystem-ci will help automate this process.

TsInfo 中使用泛型会报错

export interface ButtonProps<T> {
  /**
   * the type of button
   * @defaultValue 'default'
   */
  type?: 'primary' | 'default' | 'text'
}

报错:

UnhandledPromiseRejectionWarning: Error: unexpected declaration type in interface. name: T, kind: undefined

Support for URL params?

I'm looking to implement a route such as /posts/:id. Is this supported, and is there an example of how to access the id parameter within the page?

Documenting objects with TsInfo?

I am looking to use this plugin for a library documentation site and its going great. This is a very great plugin for that, so thank you.

We have a few spots in our library that we have objects with comments and would like to quickly display them with <TsInfo /> or something similar. Any thoughts there?

It would be something like this:

export const styles = (theme) => {
    return {
        /** Style for the button */
        button: {},
        /** @private */
        private: {}
    }
}

export const testIds = {
    /** Test id for the root container */
    ROOT: 'root-test-id'
}

Then I would want to pass the styles or testIds object to TsInfo (or something new?) to display a table with the name and comment, with the ones with no comments or @private being hidden optionally.

I am happy to submit a PR for this for the V4 work, if you have any suggestions on where to start.

Runtime code TypeScript warning

I use plugin @rollup/plugin-typescript, and get warning like below:

image

So, I think bundle of theme-doc should install antd, @ant-design/icons and so on as non-dev deps, and exclude them after bundle.

Download error in the project, the path cannot be found

image

"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"@mdx-js/mdx": "^1.6.22",
"vite": "^3.0.8",
"@mdx-js/react": "^1.6.22",
"vite-pages-theme-doc": "^3.1.4",
"vite-plugin-mdx": "^3.5.6",
"vite-plugin-react-pages": "^3.3.1"

The build command doesn't work on Windows

Hi,

I don't know where to search for this bug but it looks like that vite-plugin-react-pages doesn't support paths on Windows systems.

image

If I have time I will look into that.

windows paths broken for directory/index page routes due to trailing slashes (fix inside)

Small problem for windows paths breaking when using directory/index page routes due to trailing slashes.

Using the example here:
https://github.com/vitejs/vite-plugin-react-pages/blob/master/packages/playground/custom-find-pages2

will cause this error

image

Note: Its breaks like this by default in all the examples, not just the custom find pages demo.

Changing the config to replace \ with / fixes it. Just need to do it before pagePublicPath.replace(/\/$/, '')

/**
 * turn `sub-path/page2/index.tsx` into `/sub-path/page2`
 */
function getPagePublicPath(relativePageFilePath: string) {
  console.log('getPagePublicPath', relativePageFilePath)
  let pagePublicPath = relativePageFilePath
  .replace(/\\/g, '/') // <-- [FIX HERE] replace all the \ with / for windows paths
  .replace(/index\.(md|mdx|js|jsx|ts|tsx)$/,'')
  // remove ending slash 
  pagePublicPath = pagePublicPath.replace(/\/$/, '')
  // add starting slash
  pagePublicPath = `/${pagePublicPath}`
  return pagePublicPath
}

pretty easy to fix thanks to the excellent docs! But, it'd be nice to have in the default config too

Internal Server Error: esbuild_1.startService is not a function

While trying to reproduce #37 I stumbled upon this one. Here is the reproduction for it https://github.com/khalibloo/vite-pages-esbuild-bug
In both issues, I used the same commands on 2 different machines at the same time, and got different project scaffolding. Comparing the package.json alone shows they're very different. The machine on #37 is on node v14.17.4 and npm v6.14.14, while the one for this issue is on node v14.17.1 and npm v6.14.13. No significant version differences.

Steps (use pnpm or npm, both give the same error)

  1. Create a new vite-pages project pnpm init vite-pages app-demo --template app
  2. Install dependencies pnpm i
  3. Start dev server pnpm dev

Error message

> pnpm dev

> [email protected] dev D:\Workspace\Web\Playground\vite-pages-demo
> vite serve

(!) "alias" option is deprecated. Use "resolve.alias" instead.
Pre-bundling dependencies:
  react
  react-dom
  react-router-dom
(this will be run only when your dependencies or config have changed)

  vite v2.5.6 dev server running at:

  > Local: http://localhost:3000/
  > Network: use `--host` to expose

  ready in 1044ms.

23:47:29 [vite] new dependencies found: vite-pages-theme-basic, updating...
23:47:29 [vite] ✨ dependencies updated, reloading page...
23:47:30 [vite] Internal server error: esbuild_1.startService is not a function
  Plugin: vite-plugin-mdx
  File: D:/Workspace/Web/Playground/vite-pages-demo/pages/$.mdx
      at D:\Workspace\Web\Playground\vite-pages-demo\node_modules\.pnpm\[email protected][email protected][email protected]\node_modules\vite-plugin-mdx\dist\transform.js:47:34
      at Generator.next (<anonymous>)
      at D:\Workspace\Web\Playground\vite-pages-demo\node_modules\.pnpm\[email protected][email protected][email protected]\node_modules\vite-plugin-mdx\dist\transform.js:8:71      at new Promise (<anonymous>)
      at __awaiter (D:\Workspace\Web\Playground\vite-pages-demo\node_modules\.pnpm\[email protected][email protected][email protected]\node_modules\vite-plugin-mdx\dist\transform.js:4:12)
      at ensureEsbuildService (D:\Workspace\Web\Playground\vite-pages-demo\node_modules\.pnpm\[email protected][email protected][email protected]\node_modules\vite-plugin-mdx\dist\transform.js:45:12)
      at Object.<anonymous> (D:\Workspace\Web\Playground\vite-pages-demo\node_modules\.pnpm\[email protected][email protected][email protected]\node_modules\vite-plugin-mdx\dist\transform.js:25:31)
      at Generator.next (<anonymous>)
      at fulfilled (D:\Workspace\Web\Playground\vite-pages-demo\node_modules\.pnpm\[email protected][email protected][email protected]\node_modules\vite-plugin-mdx\dist\transform.js:5:58)

Effect of theme-doc antd global css

If I use theme doc to develop ui library, antd global css will also apply to my custom ui components. I have to override style mannually, how to make a workaround to the situation?

Maybe create a new theme without global css?

New fs-watching machanism to support hmr of all virtule modules

Virtule modules should re-render and do hmr if upstream files is updated.

Currently we only support hmr of page modules. We need a general fs-watching machanism to support hmr of all virtule modules. Demo import and tsInfo import will benefit from it.

[Feature request] Suppoert loading component

Use vite-pages-theme-doc, it will render blank area when loadState.type === 'loading', obviously not a good UX.

Support render and custom loading component is a great feature.

样式污染的问题

demo里面被 markdown的样式给覆盖了,写起来要处理很麻烦。往往出现在各种 ul li img 等等标签上
image

demo-box 我理解起来应该是干净无污染的

Pnpm Error: Failed to resolve force included dependency

It looks like some packages are being used as dependencies within this project, but not included in the package.json. Pnpm produces the error Failed to resolve force included dependency for jotai and react-router-dom. The @mdx-js/mdx and @mdx-js/react produced similar errors, but I'm not sure if you'd want to include those as dependencies in the package.json given that the mdx features are can probably be disabled if one is only interested in tsx/jsx.

Rollup failed to resolve import "react"

源码:
cd packages/create-project/template-lib-monorepo/packages/demos
npm i
npm run build
报错:
[vite]: Rollup failed to resolve import "react" from "../button/README.md".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
build.rollupOptions.external
error during build:
Error: [vite]: Rollup failed to resolve import "react" from "../button/README.md".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
build.rollupOptions.external

node 版本 v12.13.0
npm 版本 6.14.16

@pages-infra/main.js 是什么资源?

image

// index.html
<script type="module" src="/@pages-infra/main.js"></script>

克隆模板之后能用,但是在自己的项目内照着模板搞就找不到这个资源导致页面出不来。另外建议文档写个已有的项目怎么接入。

[Feature request] support for yarn2 berry

Right now it crashes with

error when starting dev server:
Error: Build failed with 1 error:
../../.pnp.js:7897:23: error: [vite:dep-scan] ENOENT: no such file or directory, open '/home/user/p/y2/.yarn/$virtual/vite-plugin-react-pages-virtual-9054c16448/0/cache/vite-plugin-react-pages-npm-2.1.0-8052dc04d7-2ba766afad.zip/node_modules/vite-plugin-react-pages/dist/client/main.js'

Uncaught TypeError: atom2.read is not a function

I get the above error in the browser console when I try to run a basic vite-react-pages app. The page crashes and nothing is displayed.

Steps to Reproduce

  1. Create a new app pnpm init vite-pages app-demo --template app
  2. Install dependencies. Install jotai because it's not included in this project's dependencies pnpm add jotai
  3. Start the app and open it in the browser.

Put the path with parameter at a later position

For example, the code looks like this:

<Switch>
  <Route path="/:id" />
  <Route path="/a" />
</Switch>

The /a will never be hit.

So I think the code in src/client/state.ts should like this:

function sortPagePaths(a: string, b: string) {
  if (a.includes('/:')) return 1;
  if (b.includes('/:')) return -1;
  if (a > b) return 1;
  if (a === b) return 0;
  if (a < b) return -1;
}
// ...
const pagePathsAtom = atom(initialPagePaths.sort(sortPagePaths));
// ...
const newPagePaths = Object.keys(newPages).sort(sortPagePaths);

In findPages, users can't overwrite exist data set by other file

In this line, I want to set page's title. But since a page is composed by multiple files. This title may have been set when another file was been processed. So this line will throw addPageData conflict: staticData with key "title" already exists.

So I am considering removing the conflict check and allow overwriting. The conflict check was added before PageStrategy API. I think it doesn't fit any more.

/cc @aleclarson

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.