Giter Club home page Giter Club logo

vite-plugin-import-build's Introduction

What is this?

This Vite plugin automatically loads your server build (i.e. your files at dist/server/).

Vite-plugin-ssr and Telefunc automatically add this plugin to your Vite app.

Manual import

Usually this Vite plugin is able to automatically import your server build (i.e. your files at dist/server/) — there is nothing for you to do.

But the plugin doesn't work if you use Yarn PnP and you'll keep getting following error. The workaround is to manually import your server build.

# Yarn PnP users always get this error:
[@brillout/vite-plugin-import-build][Wrong Usage] Cannot find server build. (Re-)build your app
and try again. If you still get this error, then you may need to manually import the server build.

⚠️ If you aren't using Yarn PnP and you keep getting this error, then it's a bug that should be fixed — please open a new issue.

To manually import your server build:

// server.js

// Load server build, see https://github.com/brillout/vite-plugin-import-build#manual-import
import './path/to/dist/server/importBuild.cjs'

// Your server code (Express.js, Vercel Serverless/Edge Function, Cloudflare Worker, ...)
// ...

Make sure to import dist/server/importBuild.cjs only in production. See Conditional manual import if your production and development share the same server entry file.

If you use vite.config.js > build.outDir then replace dist/server/importBuild.cjs with ${build.outDir}/server/importBuild.cjs.

See How it works if you're curious and/or you want to learn more.

vite-plugin-import-build's People

Contributors

0xhexe avatar brillout avatar magne4000 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

phiberber 0xhexe

vite-plugin-import-build's Issues

Bug reported in Terminal (production build)

front | Error: [@brillout/vite-plugin-import-build][Bug] You stumbled upon a bug in the source code of @brillout/vite-plugin-import-build. Reach out at https://github.com/brillout/vite-plugin-import-build/issues/new and include this error stack (the error stack is usually enough to fix the problem). (Debug info for the maintainers: {"distImporterDir":"/usr/src/app/dist/server","distImporterPathRelative":"/usr/src/app/dist/server/importBuild.cjs"})

front | at assert (/usr/src/app/node_modules/@brillout/vite-plugin-import-build/dist/utils/assert.js:10:11)
front | at loadWithNodejs (/usr/src/app/node_modules/@brillout/vite-plugin-import-build/dist/loadBuild/index.js:50:32)
front | at loadBuild (/usr/src/app/node_modules/@brillout/vite-plugin-import-build/dist/loadBuild/index.js:23:51)
front | at loadBuild (/usr/src/app/node_modules/vite-plugin-ssr/dist/cjs/node/plugin/plugins/importBuild/loadBuild.js:15:72)
front | at initGlobalContext (/usr/src/app/node_modules/vite-plugin-ssr/dist/cjs/node/runtime/globalContext.js:36:62)
front | at renderPage (/usr/src/app/node_modules/vite-plugin-ssr/dist/cjs/node/runtime/renderPage.js:22:53)
front | at file:///usr/src/app/server.js:219:31
front | at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
front | at next (/usr/src/app/node_modules/express/lib/router/route.js:144:13)
front | at Route.dispatch (/usr/src/app/node_modules/express/lib/router/route.js:114:3)

I was trying to downgrade packages to this versions
"@brillout/vite-plugin-import-build": "0.1.4",
"@brillout/import": "0.2.1"

But the issue still persists :(

can't make manual import work for me

a sample repo - https://github.com/hagaigold/temp-vite-telefunc

what I tried:

  • import './mydist/server/importBuild.cjs'
  • await import('./mydist/server/importBuild.cjs')
  • await import inside the _telefunc middleware

how to create:

  • pnpm i
  • set --outDir to something else, e.g. mydist
  • pnpm run build
  • delete node_modules
  • pnpm i
  • add manual import to server.js
  • pnpm run server:prod
> pnpm run server:prod

> @ server:prod C:\CodeW\vite_tele
> cross-env NODE_ENV=production node ./server

DEBUG: import build...

Server running at http://localhost:3001
Error: [@brillout/[email protected]][Wrong Usage] Cannot find server build. (Re-)build your app and try again. If you still get this error, then you may need to manually import the server build, see https://github.com/brillout/vite-plugin-import-build#manual-import
    at createErrorWithCleanStackTrace (C:\CodeW\vite_tele\node_modules\.pnpm\@[email protected]\node_modules\@brillout\vite-plugin-import-build\dist\utils\createErrorWithCleanStackTrace.js:9:15)
    at assertUsage (C:\CodeW\vite_tele\node_modules\.pnpm\@[email protected]\node_modules\@brillout\vite-plugin-import-build\dist\utils\assert.js:40:92)
    at loadServerBuild (C:\CodeW\vite_tele\node_modules\.pnpm\@[email protected]\node_modules\@brillout\vite-plugin-import-build\dist\loadServerBuild\index.js:37:29)
    at async loadGlobImporter (C:\CodeW\vite_tele\node_modules\.pnpm\[email protected]\node_modules\telefunc\dist\cjs\node\vite\loadTelefuncFilesWithVite.js:34:9)
    at async loadTelefuncFilesWithVite (C:\CodeW\vite_tele\node_modules\.pnpm\[email protected]\node_modules\telefunc\dist\cjs\node\vite\loadTelefuncFilesWithVite.js:10:45)
    at async loadTelefuncFiles (C:\CodeW\vite_tele\node_modules\.pnpm\[email protected]\node_modules\telefunc\dist\cjs\node\server\runTelefunc\loadTelefuncFiles.js:34:73)
    at async runTelefunc_ (C:\CodeW\vite_tele\node_modules\.pnpm\[email protected]\node_modules\telefunc\dist\cjs\node\server\runTelefunc.js:82:59)
    at async runTelefunc (C:\CodeW\vite_tele\node_modules\.pnpm\[email protected]\node_modules\telefunc\dist\cjs\node\server\runTelefunc.js:38:16)
    at async telefunc (C:\CodeW\vite_tele\node_modules\.pnpm\[email protected]\node_modules\telefunc\dist\cjs\node\server\telefunc.js:11:26)
    at async file:///C:/CodeW/vite_tele/server.js:24:26

Conditional manual import

If your production and development share the same server entry file, then you need to conditionally import importBuild.cjs.

There are multiple approaches.


1. Top-level await.

// server.js

if (process.env.NODE_ENV === 'production') {
  await import('./path/to/dist/server/importBuild.cjs')
}

// ... server code ...

For environments that don't support top-level await, see alternatives below.


2. Wrap entry code in async function.

// server.js

main()

// We wrap the entire code of server.js in an async function main()
async function main() {
  if (process.env.NODE_ENV === 'production') {
    await import('./path/to/dist/server/importBuild.cjs')
  }

  // ... server code ...
}

3. Await import() promise in middleware.

// server.js

const serverBuildPromise = getServerBuildPromise()

app.get('*', async (req, res, next) => {
  // Ensure import('./path/to/dist/server/importBuild.cjs') has finished
  await serverBuildPromise()
  // ... middleware ... (e.g. the middleware for vite-plugin-ssr or Telefunc)
})

function getServerBuildPromise() {
  if (process.env.NODE_ENV !== 'production') return
  let resolve
  const serverBuildPromise = new Promise((r) => { resolve = r })
  import('./path/to/dist/server/importBuild.cjs').then(() => {
    resolve()
  })
  return serverBuildPromise
}

The issue on Windows PC with the path with folders starting from "u."

As you can see in the error message, windows use backslash as a path delimiter. Addin' to that "u," we get a special character for the Unicode symbol, which is not what is expected here.
Adding the second backslash should escape the initial backslash, and the issue should be resolved.
Please, take a look

C:\Users\...\src\main\ui\node_modules\@brillout\vite-plugin-import-build\dist\autoImporter.js:7
  autoImporterFilePathOriginal: 'C:\Users\...\src\main\ui\node_modules\@brillout\vite-plugin-import-build\dist\autoImporter.js',
                                                      ^^^^^^

SyntaxError: Invalid Unicode escape sequence

This is the content of the file I have in my node_modules/@brillout/vite-plugin-import-build/dist/autoImporter.js. (Only one line has backslashes)

exports.status = 'SET';
exports.loadImportBuild = () => { require('../../../../src/dist/server/importBuild.cjs') };
exports.paths = {
  importBuildFilePathRelative: '../../../../src/dist/server/importBuild.cjs',
  importBuildFilePathResolved: () => require.resolve('../../../../src/dist/server/importBuild.cjs'),
  importBuildFilePathOriginal: 'C:/Users/.../src/main/ui/src/dist/server/importBuild.cjs',
  autoImporterFilePathOriginal: 'C:\Users\...\src\main\ui\node_modules\@brillout\vite-plugin-import-build\dist\autoImporter.js',
};
exports.load = exports.loadImportBuild;

How it works

⚠️ This is for expert users who want to know how @brillout/vite-plugin-import-build works. Do NOT read this if you merely want to solve your problem, see the README instead.

@brillout/vite-plugin-import-build uses two tricks to automagically load your server build. (I.e. to automagically load your server files built at dist/server/, or ${build.outDir}/server in case you use vite.config.js#build.outDir.)

Trick 1

Trick 1: @brillout/vite-plugin-import-build dynamically generates a file that imports dist/server/importBuild.cjs on your behalf:

// node_modules/@brillout/vite-plugin-import-build/dist/autoImporter.js

require('../../../dist/server/importBuild.cjs');

If you use vite.config.js#build.outDir, then the path is generated accordingly. (I.e. dist/ is replaced with your build.outDir value.)

The dist/server/importBuild.cjs file is generated by @brillout/vite-plugin-import-build and acts as the entry of the server build; see its content $ cat dist/server/importBuild.cjs.

But this trick doesn't work:

  • If you install npm packages after you build your app (i.e. after running $ vite build).

    Because @brillout/vite-plugin-import-build generates node_modules/@brillout/vite-plugin-import-build/dist/autoImporter.js at build-time (when running $ vite build). So, if we $ rm -r node_modules/ && npm install, then the generated file node_modules/@brillout/vite-plugin-import-build/dist/autoImporter.js is erased.

  • When using Yarn PnP which installs dependencies in an immutable way.

    Because @brillout/vite-plugin-import-build cannot generate node_modules/@brillout/vite-plugin-import-build/dist/autoImporter.js.

In theses situations, @brillout/vite-plugin-import-build uses a second trick.

Trick 2

Trick 2: @brillout/vite-plugin-import-build dynamically searches for dist/server/importBuild.cjs and dynamically loads it.

But that doesn't work:

  • If you use vite.config.js#build.outDir.

    Because the config values set by vite.config.js aren't available to the production runtime. (The vite.config.js configuration is meant for transpilation, not for the production runtime.) Thus the build.outDir value is unknown to the production runtime.

  • In edge environments where dynamically importing modules isn't possible (e.g. Cloudflare Workers).
  • If you want to bundle all our server code into a single file.

Fallback

If both tricks don't work, then you can fallback to manually importing dist/server/importBuild.cjs, as described in the README.

You need the fallback only if both tricks 1 and trick 2 don't work which, all-in-all, is a rare situation.

Failed to build when --watch is enabled

I'm trying to use vite build --watch and everytime I got the following error.

Error: [@brillout/vite-plugin-import-build][Bug] You stumbled upon a bug in the source code of @brillout/vite-plugin-import-build. Reach out at https://github.com/brillout/vite-plugin-import-build/issues/new and include this error stack (the error stack is usually enough to fix the problem). (Debug info for the maintainers: {"distImporterDir":"/react-node-ssr/dist/server","distImporterPathRelative":"/react-node-ssr/dist/server/importBuild.cjs"})
at assert (/react-node-ssr/node_modules/@brillout/vite-plugin-import-build/dist/utils/assert.js:10:11)
at loadWithNodejs (/react-node-ssr/node_modules/@brillout/vite-plugin-import-build/dist/loadBuild/index.js:49:32)
at loadBuild (/react-node-ssr/node_modules/@brillout/vite-plugin-import-build/dist/loadBuild/index.js:23:51)
at loadBuild (/react-node-ssr/node_modules/vite-plugin-ssr/dist/cjs/node/plugin/plugins/importBuild/loadBuild.js:15:72)
at getGlobalContext (/react-node-ssr/node_modules/vite-plugin-ssr/dist/cjs/node/globalContext.js:29:62)
at prerender (/react-node-ssr/node_modules/vite-plugin-ssr/dist/cjs/node/prerender.js:42:70)
at async triggerFullBuild (/react-node-ssr/node_modules/vite-plugin-ssr/dist/cjs/node/plugin/plugins/autoFullBuild.js:57:9)
at async Object.writeBundle (/react-node-ssr/node_modules/vite-plugin-ssr/dist/cjs/node/plugin/plugins/autoFullBuild.js:23:17)
at async Promise.all (index 0)
at async PluginDriver.hookParallel (file:///react-node-ssr/node_modules/rollup/dist/es/shared/rollup.js:22638:9)
at async file:///react-node-ssr/node_modules/rollup/dist/es/shared/rollup.js:23763:13
at async catchUnfinishedHookActions (file:///react-node-ssr/node_modules/rollup/dist/es/shared/rollup.js:23088:20)
at async Promise.all (index 0)
at async Task.run (file:///react-node-ssr/node_modules/rollup/dist/es/shared/watch.js:4944:32)
at async Watcher.run (file:///react-node-ssr/node_modules/rollup/dist/es/shared/watch.js:4871:13)

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.