@webfox/laravel-vite
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

Webfox Vite

Webfox's custom vite set up. Below is a guide on how to switch an encore project to using vite.

Authors

Matthew Hailwood, (Mad Dev who made the plugin)
Jim Hulena, (The guy who wrote the guide)

How to switch old laravel projects using encore

Disclaimer: This may not be a "one size fits all", there will likely be other issues you encounter, though we are more than happy to help.

  1. npm install @vitejs/plugin-react vite-plugin-restart
  2. npm install react-dom @inertiajs/inertia-react @inertiajs/progress
  3. refactor app.js to app.tsx
  4. copy and paste below into app.tsx. Ensure you have FormErrorContextProvider and InitialApplicationContext
import MainLayout from './Layouts/MainLayout';
import {initInertiaApp} from 'Support/init';
import 'Style/app.css';

initInertiaApp({
  resolve: async name => {
    const comps = import.meta.glob('./Pages/**/*.jsx'); //Can be jsx or tsx depending on your langauge preference
    const match = comps[`./Pages/${name}.jsx`]; //same as above comment
    return (await match()).default;
  },
  layout: MainLayout,
});
  1. Create init.tsx in Support directory
  2. Copy and paste below into init.tsx
import {Inertia} from '@inertiajs/inertia';
import {createInertiaApp, PageResolver} from '@inertiajs/inertia-react';
import {InertiaProgress, ProgressSettings} from '@inertiajs/progress';
import * as React from 'react';
import {createRoot} from 'react-dom/client'
import {ComponentType, createElement, PropsWithChildren, ReactElement, StrictMode} from 'react';
import {FormErrorContextProvider, InitialApplicationContext} from './Contexts';
import 'Support/yupExtensions';

// export const initGoogleAnalytics = () => {
//   if (typeof window.gtag === 'function') {
//     let initialPageView = true;
//     Inertia.on('navigate', (event) => {
//       if (initialPageView) {
//         initialPageView = false;
//       } else {
//         window.gtag('event', 'page_view', {
//           'page_location': event.detail.page.url,
//         });
//       }
//     });
//   }
// };
//
// export const initErrorTracking = async () => {
//   if (window.sentryDsn) {
//     const Sentry = await import('@sentry/react');
//     const {BrowserTracing} = await import('@sentry/tracing');
//
//     Sentry.init({
//       dsn: window.sentryDsn,
//       integrations: [new BrowserTracing()],
//       environment: window.sentryEnvironment,
//       tracesSampleRate: window.sentryTracesSampleRate,
//     });
//   }
// };

export const initInertiaApp = ({
  resolve,
  layout: MainLayout,
  analytics = true,
  errorTracking = true,
  inertiaProgress = true,
}: {
  resolve: PageResolver;
  layout: ComponentType<PropsWithChildren>;
  analytics?: boolean;
  errorTracking?: boolean;
  inertiaProgress?: boolean | ProgressSettings;
}) => {
  // if (errorTracking) {
  //   initErrorTracking();
  // }
  //
  //
  // if (analytics) {
  //   initGoogleAnalytics();
  // }

  if (inertiaProgress) {
    InertiaProgress.init(typeof inertiaProgress === 'boolean' ? {
      showSpinner: true,
    } : inertiaProgress);
  }

  return createInertiaApp < Window['inertiaInitialPageData']['props'] > ({
    resolve,
    page: window.inertiaInitialPageData,
    setup({el, App, props}) {
      createRoot(el).render((
        <StrictMode>
          <InitialApplicationContext.Provider value={{application: props.initialPage.props.application}}>
            <App {...props}>
              {({key, props, Component}) => {
                // @ts-ignore
                const componentLayout: (page: ReactElement) => ReactElement | Array<(page: ReactElement) => ReactElement> = Component.layout;
                const page = createElement(Component, {key, ...props});
                let children;

                if (Array.isArray(componentLayout)) {
                  children = componentLayout.concat(page).reverse().reduce((children, Layout) => createElement(Layout, {children}));
                } else if (typeof componentLayout === 'function') {
                  children = componentLayout(page);
                } else {
                  children = <MainLayout children={page}/>;
                }

                return (
                  <FormErrorContextProvider>
                    {children}
                  </FormErrorContextProvider>
                );
              }}
            </App>
          </InitialApplicationContext.Provider>
        </StrictMode>
      ));
    },
  });
};
  1. create vite.config.ts in root directory
  2. copy below into vite.config.ts
import react from '@vitejs/plugin-react';
import laravel from '@webfox/laravel-vite';
import {defineConfig} from 'vite';
import viteRestart from 'vite-plugin-restart';

export default defineConfig({
  plugins: [
    laravel(['resources/app/js/app.tsx',]),
    react(),
    viteRestart({
      restart: 'tsconfig.json',
    }),
  ],
  server: {
    host: 'localhost',
    hmr: {
      host: 'localhost',
    },
    https: {
      key: process.env.WEBPACK_KEY,
      cert: process.env.WEBPACK_CERT,
    },
  },
  css: {
    postcss: {
      plugins: [
        require('postcss-import')(),
        require('tailwindcss')(),
        require('autoprefixer')(),
      ],
    },
  },
});
  1. Replace 'resources/app/js/app.tsx' with the path to your app.tsx
  2. Add @viteReactRefresh and @vite('resources/app/js/app.tsx') to the body of your app.blade.php
  3. Remove all Encore related code from app.blade.php
  4. In helper.php remove function encore
  5. Select all js files in PHPStorm, right click and select "Override file type" and search for jsx. (All files need to be jsx)
  6. In package.json replace "Scripts" with below
 "scripts": {
    "hot": "cross-env NODE_ENV=development vite",
    "prod": "cross-env NODE_ENV=production vite build"
  },
  1. create tsconfig.json in root directory
  2. copy and paste below into tsconfig.json
{
  "include": [
    "resources/app/js/**/*",
    "resources/app/css/**/*",
    "resources/app/images/**/*"
  ],
  "compilerOptions": {
    "rootDir": ".",
    "incremental": true,
    "allowJs": true,
    "noErrorTruncation": true,
    "lib": [
      "ESNext",
      "DOM"
    ],
    "target": "ESNext",
    "module": "ESNext",
    "sourceMap": true,
    "isolatedModules": true,
    "experimentalDecorators": true,
    "moduleResolution": "Node",
    "noImplicitOverride": true,
    "strictNullChecks": true,
    "esModuleInterop": true,
    "jsx": "react-jsx",
    "paths": {
      "Components": [
        "./resources/app/js/Components"
      ]
    }
  }
}
  1. replace path object with your aliases in the same format as Components

Dependents (0)

Package Sidebar

Install

npm i @webfox/laravel-vite

Weekly Downloads

0

Version

1.2.0

License

MIT

Unpacked Size

40.1 kB

Total Files

7

Last publish

Collaborators

  • webfoxdev