Skip to content
This repository has been archived by the owner on Aug 28, 2021. It is now read-only.

Commit

Permalink
Workaround node core module import failures in dev
Browse files Browse the repository at this point in the history
  • Loading branch information
wlib committed Jul 2, 2021
1 parent 5653d8d commit 607273b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Install

`npm i -D vite-plugin-bruh` or use `npm init bruh` with the `vite-ssr` template to quickly get started.
`npm i -D vite-plugin-bruh` or use `npm init bruh` with the `vite` template to quickly get started.

## Use

Expand Down Expand Up @@ -85,3 +85,18 @@ touch prerendering the html.
Keep in mind that until (if) vite allows dynamic entry points, the `x.html.mjs` files must be be executable by node directly.
This means no jsx or vite-specific tooling within these files and their imports.
Also, vite currently needs an explicit array of node core modules that it should allow to passthrough its module graph.
You need to specify them in the `external` option, the defaults are just `["fs", "path", "crypto"]` right now.
If you want to use `import.meta.url`, vite will currently give a (non URL!) absolute path that is "relative" to your vite `root`.
The easiest workaround is to just do something like this:
```javascript
import path from "path"

// A path relative to where the `vite` command is run
path.resolve("a/path/relative/to/the/vite/currentWorkingDirectory")

// Instead of what you would expect to work
new URL("a/path/relative/to/this/file", import.meta.url).pathname
```
20 changes: 17 additions & 3 deletions index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const getHtmlRenderFiles = async (directory, maxDepth = Infinity) => {
}
}

export const bruhDev = ({ root } = {}) => {
export const bruhDev = ({ root, external } = {}) => {
const urlToHtmlRenderFile = async url => {
const pathname = path.join(root, path.normalize(url))
const htmlRenderFiles = await getHtmlRenderFiles(path.dirname(pathname), 2)
Expand All @@ -51,6 +51,14 @@ export const bruhDev = ({ root } = {}) => {
apply: "serve",
enforce: "pre",

config() {
return {
ssr: {
external
}
}
},

configureServer(viteDevServer) {
viteDevServer.middlewares.use(async (req, res, next) => {
try {
Expand Down Expand Up @@ -144,9 +152,15 @@ export const bruhJSX = () => {
}
}

export const bruh = ({ root } = {}) =>
export const bruh = ({
root,
external = []
} = {}) =>
[
bruhDev({ root }),
bruhDev({
root,
external: ["fs", "path", "crypto", ...external]
}),
bruhBuild({ root }),
bruhJSX()
]
Expand Down

0 comments on commit 607273b

Please sign in to comment.