A Marko plugin for Vite

Related tags

Vue.js vite
Overview


@marko/vite
TypeScript Styled with prettier Build status NPM Version Downloads

A Marko plugin for Vite.

Installation

npm install @marko/vite

Example config

import { defineConfig } from "vite";
import marko from "@marko/vite";
export default defineConfig({
  plugins: [marko()],
});

Linked Mode

By default this plugin operates in linked mode (you can disabled this by passing linked: false as an option). In linked mode the plugin automatically discovers all of the entry .marko files while compiling the server, and tells Vite which modules to load in the browser.

With this you do not create .html files for Vite, it's Marko all the way down! Scripts, styles and other content that would have been injected into the .html files is instead automatically injected into your .marko templates.

In this mode you must use the Vite SSR API.

Here's an example using express.

import { createServer } from "vite";

const app = express();
let loadTemplate;

if (process.env.NODE_ENV === "production") {
  // Use Vite's built asset in prod mode.
  loadTemplate = () => import("./dist");
} else {
  // Hookup the vite dev server.
  const vite = await createViteServer({
    server: { middlewareMode: true }
  });

  app.use(vite.middlewares);
  loadTemplate = () => vite.ssrLoadModule("./template.marko");
}

app.get("/", async (req, res) => {
  const template = (await loadTemplate()).default;
  // When the template is loaded, it will automaticall have `vite` assets inlined.
  template.render({ hello: "world" }, res);
);

app.listen(3000);

For a more real world setup check out our vite express example app.

Options

options.babelConfig

You can manually override Marko's Babel configuration by passing a babelConfig object to the @marko/vite plugin. By default Babel's regular config file resolution will be used.

marko({
  babelConfig: {
    presets: ["@babel/preset-env"],
  },
});

options.runtimeId

In some cases you may want to embed multiple isolated copies of Marko on the page. Since Marko relies on some window properties to initialize this can cause issues. For example, by default Marko will read the server rendered hydration code from window.$components. In Marko you can change these window properties by rendering with { $global: { runtimeId: "MY_MARKO_RUNTIME_ID" } } as input on the server side.

This plugin exposes a runtimeId option produces output that automatically sets $global.runtimeId on the server side and initializes properly in the browser.

marko({ runtimeId: "MY_MARKO_RUNTIME_ID" });

options.linked

Set this to false to opt out of linked mode. When this is false, the plugin will only handle resolving and transforming .marko files.

Code of Conduct

This project adheres to the eBay Code of Conduct. By participating in this project you agree to abide by its terms.

Comments
  • feat: optimize marko deps

    feat: optimize marko deps

    Resolves #12 This PR tries to enables optimizing deps (vite) on marko files through bringing an esbuild plugin and add .marko extension to optimizeDeps option. Tried with @marko-tags/match-media and it works well!

    released 
    opened by Aslemammad 4
  • fix: switch to mutation style for vite config mutations

    fix: switch to mutation style for vite config mutations

    Description

    The Vite config plugin hook exposes two apis. You can either mutate the provided config, or return a new config that is deep merged.

    For some reason we were doing both which may have been leading to some issues.

    This PR updates the code in that plugin hook to only use the mutation style api.

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    opened by DylanPiercey 2
  • fix: avoid using Vite's load api

    fix: avoid using Vite's load api

    Description

    Vite's .load api in the plugin context seems to have issues. Specifically it was found that when using the Marko plugin with many entry Marko files that it would break when using the load api.

    Instead this PR saves the entry files sources along with the rest of the server manifest and uses that.

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    opened by DylanPiercey 2
  • Vite 3

    Vite 3

    Description

    • Improve support for Vite 3
    • Fix issue with linked: false server only builds attempting to render assets
    • Some refactoring.
    • Dev config improvements

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [x] I have added tests to cover my changes.
    opened by DylanPiercey 2
  • fix: revert #16

    fix: revert #16

    Description

    Reverts #16 since it ultimately causes all assets to be injected before any html has been rendered.

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    released 
    opened by DylanPiercey 2
  • refactor: use internal _vite tag instead of generating code to call __viteRenderAssets

    refactor: use internal _vite tag instead of generating code to call __viteRenderAssets

    Description

    Motivation and Context

    Screenshots (if appropriate):

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    opened by mlrawlings 2
  • fix: always pass resolveVirtualDependencies compiler option

    fix: always pass resolveVirtualDependencies compiler option

    Description

    Updates the compiler options to always pass the resolveVirtualDependencies config option. Previously It was not passed for SSR compilation.

    Motivation and Context

    In the future this option may be used to enable native css module support within Marko templates and other features.

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    released 
    opened by DylanPiercey 2
  • second regex capture to grab hmr rendered marko files

    second regex capture to grab hmr rendered marko files

    ##Description

    vite HMR builds add a t=____ string to the end of marko files that was failing to match the original regex. so, I added a second one.

    Motivation and Context

    HMR refreshes in vite would kill the page until the server was restarted

    Checklist:

    • [n/a] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    released 
    opened by jwise7 2
  • fix: upgrade deps, improve entry file detection

    fix: upgrade deps, improve entry file detection

    Description

    • Upgrade all deps
    • Fix support for using .marko file as a <script> src for the top level html file (now includes only hydrate code).
    • Test cleanup to remove hashes

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [x] I have added tests to cover my changes.
    released 
    opened by DylanPiercey 2
  • Uncaught TypeError: out.global.___viteRenderAssets is not a function

    Uncaught TypeError: out.global.___viteRenderAssets is not a function

    Version: 1.3.2 & 2.0.0

    I have tested with 1.3.2 and 2.0.0.

    Details

    Uncaught TypeError: out.global.___viteRenderAssets is not a function
        at _marko_template._._marko_renderer.t (app-layout.marko:19)
        at renderer (renderer.js:218)
        at proxyRenderer (hot-reload.js:73)
        at AppLayout.___rerender (Component.js:552)
        at hydrateComponentAndGetMount (index-browser.js:427)
        at tryHydrateComponent (index-browser.js:387)
        at index-browser.js:365
        at Array.map (<anonymous>)
        at Object.initServerRendered [as concat] (index-browser.js:361)
        at index-browser.js:293
    

    app-layout.marko:19 is only a <head> tag

    It's ok if I remove the js from the app-layout.marko. Also, If I don't provide data from res.marko() is ok.

    Just for info, By searching in the final js I found t.global.___viteRenderAssets(t, "head-prepend").

    Expected Behavior

    Run without Uncaught TypeError: out.global.___viteRenderAssets is not a function error, because this error breaks the execution of the JS, it is currently unusable.

    Actual Behavior

    Built on the server side but does not execute in the browser because of this error

    Possible Fix

    Serialization may be the cause? (res.marko() and res.locals seems to be impacted)

    Your Environment

    Ubuntu 18.04 Node v14.15.4

    I have updated the dependencies of the skeleton (but the bug is perhaps present on the original skeleton):

    "dependencies": {
        "@marko/express": "^1.0.0",
        "express": "^4.17.1",
        "marko": "^5.15.1",
        "raptor-pubsub": "^1.0.5"
      },
      "devDependencies": {
        "@marko/compiler": "^5.15.0",
        "@marko/vite": "^2.0.0",
        "cross-env": "^7.0.3",
        "marked": "^2.1.3",
        "rimraf": "^3.0.2",
        "vite": "^2.4.4"
      },
    

    Steps to Reproduce

    Generate a vite express project with:

    npx @marko/create
    

    Replace app-layout/app-layout.marko content by this:

    class {
      onCreate(input) {
        this.state = {
          pageTitle: input.pageTitle
        };
      }
    }
    
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="description" content="An example application showcasing Vite & Marko.">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <${input.head}/>
      </head>
      <body>
        <sample-header title="Marko UI Components Playground"/>
        <div class="container">
          <main id="main">
            <h1>${state.pageTitle}</h1>
            <${input.body}/>
          </main>
        </div>
      </body>
    </html>
    

    And replace _./pages/index/index.js` content by this:

    import template from "./template.marko";
    
    export default (req, res) => {
      res.marko(template, {
        pageTitle: 'Welcome to my page',
      });
    };
    

    Then run:

    npm run dev
    

    or:

    npm run build && npm run start
    

    Stack Trace

    Uncaught TypeError: out.global.___viteRenderAssets is not a function
        at _marko_template._._marko_renderer.t (app-layout.marko:19)
        at renderer (renderer.js:218)
        at proxyRenderer (hot-reload.js:73)
        at AppLayout.___rerender (Component.js:552)
        at hydrateComponentAndGetMount (index-browser.js:427)
        at tryHydrateComponent (index-browser.js:387)
        at index-browser.js:365
        at Array.map (<anonymous>)
        at Object.initServerRendered [as concat] (index-browser.js:361)
        at index-browser.js:293
    
    opened by Nicolab 2
  • fix: remove semicolon from _vite tag

    fix: remove semicolon from _vite tag

    Description

    Motivation and Context

    Screenshots (if appropriate):

    Checklist:

    • [ ] I have updated/added documentation affected by my changes.
    • [ ] I have added tests to cover my changes.
    released 
    opened by mlrawlings 1
  • Marko doesn't recognize new components after first build

    Marko doesn't recognize new components after first build

    Version: 2.3.9

    Details

    After starting the dev server I created a new component and tried using it. Marko didn't recognize it, needed restart of the server

    Expected Behavior

    I expected the component will be recognized and be able to be used without restart

    opened by Hen2609 0
  • "preserve-tag" is not supported resolving ES modules

    Version: 2.3.9

    Details

    When using the no-update attribute on an element, our production builds break with the following error:

    Directory import '.../node_modules/marko/dist/core-tags/components/preserve-tag' is not supported resolving ES modules imported from '.../dist/index.js' Did you mean to import marko/dist/core-tags/components/preserve-tag/index.js?

    We are able to work around it by manually changing the following line in our build output from: import _preserve from "marko/dist/core-tags/components/preserve-tag"; to import _preserve from "marko/dist/core-tags/components/preserve-tag/index.js";

    Additional Info

    Your Environment

    Node 16.14.0

    opened by JPritchard9518 0
  • Import client side modules in ssr mode

    Import client side modules in ssr mode

    Hey :) Is it possible to import client side modules in server side rendering mode at the top of a component? I try to use Bootstrap for example, but I can't import the js into my marko component, because window.document don't exists on the server side. Is there a way to tell marko or vite that the component uses client side modules or should the plugin already recognize that and this is a common bug?

    I work with the vite-express example and try to import Bootstrap components into my marko component.

    import { Tooltip, Toast, Popover } from 'bootstrap'
    

    I can import all of Bootstrap js into a single client js file, set the bootstrap variable as global window variable and load this file as module in my apps html head with a script tag. In this case it is working fine but this scenario won't work for all cases like the import of external marko components which are import client side code directly.

    I don't know if this is the right Repo for reporting this issue or if I am on the wrong way here but I cannot find a solution for this.

    opened by asieverding 2
  • HMR not working on at least some components that don't have a class defined

    HMR not working on at least some components that don't have a class defined

    Version: 2.2.11

    Details

    When updating components like the sample-header in the vite-express example app it doesn't trigger an automatic refresh of the component in the browser. A manual page reload does in fact show that the change did occur, but it doesn't happen automatically like it would when editing a component that has a class defined.

    Expected Behavior

    the page could either trigger a full reload automatically, or update the component seamlessly in the browser.

    Actual Behavior

    the page stays the same until you perform a manual reload

    Possible Fix

    I haven't traced this all the way through to completely suggest a fix, but from my initial investigation this may just be a limitation/feature of marko because it's compiling non-class based widgets into plain out.w statements of the html. for example, with the sample-header component mentioned above, the code for it gets put into the app-main\index.marko output as out.w(\"<h1>\");\n out.w(\"Hello!\");\n out.w(\"</h1>\") (you can see this when inspecting the source variable in this function of marko vite.

    Additional Info

    Your Environment

    Windows 11 Edge 100.0.1185.29 node 16.14.2

    Steps to Reproduce

    1. npm run dev in the vite-express example
    2. edit the sample-header title to have something extra, then save it
    3. notice that it didn't perform the HMR update in browser

    Stack Trace

    no error thrown, just an undefined mod variable in vite's code here: async function fetchUpdate({ path, acceptedPath, timestamp }: Update) { const mod = hotModulesMap.get(path) if (!mod) {

    opened by jwise7 0
Releases(v2.3.9)
Owner
Marko
Marko
Vue 3 + Vite + SSR template based on Vite Plugin SSR and inspired by Vitesse

Vite Vue SSR Starter Vue 3 + Vite + SSR template based on Vite Plugin SSR and inspired by Vitesse Features ⚡️ Vue 3, Vite 2, TypeScript ?? Domain-Driv

Oleg Koval 10 Aug 2, 2022
Vite Svelte plugin to remove console logs in prod.

vite-plugin-svelte-console-remover A Vite plugin that removes all console statements (log, group, dir, error, etc) from Svelte, JS, and TS files durin

Josh Hubbard 29 Oct 13, 2022
A vite plugin that deletes console.log in the production environment

vite-plugin-remove-console A vite plugin that deletes console.log in the production environment English | 中文 Install npm install vite-plugin-remove-co

啝裳 49 Dec 22, 2022
A progress bar plugin for Vite.

vite-plugin-progress Display with progress bar when building ?? Install npm i vite-plugin-progress -D # yarn yarn add vite-plugin-progress -D # pn

Jeddy Gong 137 Dec 17, 2022
Laravel plugin for Vite.

Laravel Vite Plugin Introduction Vite is a modern frontend build tool that provides an extremely fast development environment and bundles your code fo

The Laravel Framework 580 Jan 7, 2023
🐝 A vite plugin automatically export files & HMR support

vite-plugin-hot-export Automatically export files with HMR English|简体中文 Why ? When developing, we often need to download some images or svg from the i

Frozen FIsh 54 Nov 12, 2022
Vite plugin for minifying / obfuscating CSS classes in production builds

vite-plugin-class-mangler Vite plugin for minifying / obfuscating classes in production builds. Compatible with Tailwind, inline, or imported styles.

Maxim 28 Dec 22, 2022
Rust dbg! in js powered by rollup/vite plugin system

rollup-plugin-dbg This plugin is also compatible with vite use with rollup import { defineConfig } from "rollup"; import config from "./package.json";

Jason 17 Aug 18, 2022
⚡️🌱 Vite plugin for Twig, transforms twig templates into HTML

⚡️ ?? ViteTwig import twig from '@vituum/vite-plugin-twig' export default { plugins: [ twig({ reload: true, root: null, filte

Vituum 7 Dec 15, 2022
A Vite plugin for projecting your application onto a remote production page during development.

vite-plugin-proxy-page A Vite plugin for developing an SPA in the context of a deployed production page. What's the Problem? It's an increasingly comm

Alex MacArthur 13 Nov 13, 2022
✅ Vite plugin for validating your environment variables

This Vite plugin allows you to validate your environment variables at build or dev time. This allows your build/dev-server to fail-fast if your setup

Julien Ripouteau 61 Dec 23, 2022
🎉 基于 vite 2.0 + vue 3.0 + vue-router 4.0 + vuex 4.0 + element-plus 的后台管理系统vue3-element-admin

vue3-element-admin ?? 基于 Vite 2.0 + Vue3.0 + Vue-Router 4.0 + Vuex 4.0 + element-plus 的后台管理系统 简介 vue3-element-admin 是一个后台前端解决方案,它基于 vue3 和 element-plu

雪月欧巴 84 Nov 28, 2022
Vite template with TypeScript, Chakra UI, Eslint Airbnb, Prettier

Vite + Typescript + ChakraUI = ❤️ This is a vite template that combines several technologies: Vite React TypeScript ChakraUI Eslint with eslint-config

Lorenzo Rapetti 3 Mar 26, 2022
Integrate Tauri in a Vite project to build cross-platform apps.

vite-plugin-tauri Integrate Tauri in a Vite project to build cross-platform apps Install Make sure to setup your environment for Tauri development. Th

Amr Bashir 95 Dec 15, 2022
A template repository / quick start to build Azure Static Web Apps with a Node.js function. It uses Vue.js v3, Vue Router, Vuex, and Vite.js.

Azure Static Web App Template with Node.js API This is a template repository for creating Azure Static Web Apps that comes pre-configured with: Vue.js

Marc Duiker 6 Jun 25, 2022
⏳ vue3 + electron + ts + vite = mini template

v3-electron ?? Electron16 + Vue3 + Vite2 运行项目 # enter the project directory cd v3-electron # install dependency yarn # develop yarn dev # build exe

UNPany 8 Nov 11, 2022
Using Cypress with Vite, React, TypeScript, MSW and react-query

Vie + Cypress + MSW + react-query Demo Example of using Cypress with Vite, MSW and react-query. Uses the appReady pattern to signal to Cypress when th

Rob Caldecott 9 Jul 16, 2022
Fastify boilerplate with Vite & Vitest

Fastify boilerplate with Vite & Vitest Enhance your Fastify DX with the power of Vite & Vitest. Features ⚡ All the power of Vite (Next Generation Fron

Emmanuel Salomon 31 Dec 13, 2022
Some compile-time magic for your Vite project

?? You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. vite-plugin-compile-time Use this plugin to generate

EGOIST 90 Dec 15, 2022