Code Monkey home page Code Monkey logo

craft-vite's Introduction

Scrutinizer Code Quality Code Coverage Build Status Code Intelligence Status

Vite plugin for Craft CMS 5.x

Allows the use of the Vite.js next generation frontend tooling with Craft CMS

Screenshot

Related Article: Vite.js Next Generation Frontend Tooling + Craft CMS

Most of the magic is actually in the nystudio107/craft-plugin-vite package, so that Craft CMS plugins can use it too.

Requirements

This plugin requires Craft CMS 5.0.0 or later.

Installation

  1. Install with Composer via composer require nystudio107/craft-vite from your project directory
  2. Install the plugin via php craft install/plugin vite via the CLI -or- in the Craft Control Panel under Settings > Plugins

You can also install Vite via the Plugin Store in the Craft Control Panel.

Documentation

Click here -> Vite Documentation

Brought to you by nystudio107

craft-vite's People

Contributors

johndwells avatar khalwat avatar michaelrog 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

craft-vite's Issues

Can't make HMR detect TWIG changes

Question

I'm trying to configure Vite with HMR for twig pages, as said in the documentation https://nystudio107.com/docs/vite/#live-reload-of-twig-config but it doesn't seem to work.

My project is just a vanila CraftCMS installation with the craft-vite plugin installed and some twig templates under the templates folder
I've created a src/js/app.ts inside the project, with the following content:

import "/templates/static/modules/_css_global/style.less"

console.log("start");

I've created a vite.config.js file in the root:

import ViteRestart from 'vite-plugin-restart';

// https://vitejs.dev/config/
export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: './src/js/app.ts',
      }
    },
  },
  plugins: [
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
  ],
});

I've created a config/vite.php file with the following contents:

return [

   /**
    * @var bool Should the dev server be used?
    */
    'useDevServer' => App::env('ENVIRONMENT') === 'dev',

    /**
     * @var string File system path (or URL) to the Vite-built manifest.json
     */
    'manifestPath' => '@webroot/dist/manifest.json',

    /**
     * @var string The public URL to the dev server (what appears in `<script src="">` tags
     */
    'devServerPublic' => 'http://localhost:3000/',

    /**
     * @var string The public URL to use when not using the dev server
     */
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',

    /**
     * @var string The JavaScript entry from the manifest.json to inject on Twig error pages
     *              This can be a string or an array of strings
     */
    'errorEntry' => '',

    /**
     * @var string String to be appended to the cache key
     */
    'cacheKeySuffix' => '',

    /**
     * @var string The internal URL to the dev server, when accessed from the environment in which PHP is executing
     *              This can be the same as `$devServerPublic`, but may be different in containerized or VM setups.
     *              ONLY used if $checkDevServer = true
     */
    'devServerInternal' => '',

    /**
     * @var bool Should we check for the presence of the dev server by pinging $devServerInternal to make sure it's running?
     */
    'checkDevServer' => false,
];

I've created a twig file with the following line head section
{{ craft.vite.script("/src/js/app.ts") }}

Vite is detecting LESS (CSS) changes and reloading the page, but not TWIG changes. It looks like it starts fine according to the console logs
image

Any clues about what is happening here? I'm on Windows. PHP runs with a XAMPP server (PHP 7.4), whereas vite.js runs by typing npm run dev
image

Thanks

Additional context

Also, I've configured a new project from https://github.com/nystudio107/craft/tree/craft-vite and it does detect twig changes, but as soon as I remove vue (which I don't need in my project) it stops working. It looks like HMR for twig is done through a Vue.js component, is that correct?

Installation fails with Craft 4

Describe the bug

On a blank installation of Craft 4, this plugin fails to install

To reproduce

Steps to reproduce the behaviour:

  1. Create craft instance with composer create-project craftcms/craft my/project/path dev-craft4
  2. Use nitro add to initialize local environment
  3. In Control panel, try to install the Vite plugin

Then got this error

Composer output: Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- nystudio107/craft-vite 4.0.0-beta.4 requires nystudio107/craft-plugin-vite ^4.0.0-beta.3 -> found nystudio107/craft-plugin-vite[4.0.0-beta.3, v4.x-dev] but it does not match your minimum-stability.
- Root composer.json requires nystudio107/craft-vite 4.0.0-beta.4 -> satisfiable by nystudio107/craft-vite[4.0.0-beta.4].

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

I added the following to get past that error

  "minimum-stability": "dev",
  "prefer-stable": true

But that only brought me to the next error

Error: Composer\Util\Filesystem::filePutContentsIfModified(): Argument #2 ($content) must be of type string, bool given, called in /app/vendor/composer/composer/src/Composer/Repository/FilesystemRepository.php on line 165

Composer output: Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 93 updates, 0 removals
- Upgrading cebe/markdown (1.2.1 9bac5e9 => 1.2.1)
- Upgrading commerceguys/addressing (v1.3.0 566febd => v1.3.0)
- Upgrading composer/ca-bundle (1.3.1 4c67918 => 1.3.1)
- Upgrading composer/composer (2.3.5 50c47b1 => 2.3.5)
- Upgrading composer/metadata-minifier (1.0.0 c549d23 => 1.0.0)
- Upgrading composer/pcre (3.0.0 e300eb6 => 3.0.0)
- Upgrading composer/semver (3.3.2 3953f23 => 3.3.2)
- Upgrading composer/spdx-licenses (1.5.6 a30d487 => 1.5.6)
- Upgrading composer/xdebug-handler (3.0.3 ced2996 => 3.0.3)
- Upgrading craftcms/cms (4.0.0-RC1 daac7c1 => 4.0.0-RC1)
- Upgrading craftcms/oauth2-craftid (1.0.0.1 3f18364 => 1.0.0.1)
- Upgrading craftcms/plugin-installer (1.5.7 23ec472 => 1.5.7)
- Upgrading craftcms/server-check (2.1.4 c262ebd => 2.1.4)
- Upgrading creocoder/yii2-nested-sets (0.9.0 cb8635a => 0.9.0)
- Upgrading defuse/php-encryption (v2.3.1 7788048 => v2.3.1)
- Upgrading doctrine/collections (1.6.8 1958a74 => 1.6.8)
- Upgrading doctrine/lexer (1.2.3 c268e88 => 1.2.3)
- Upgrading egulias/email-validator (3.1.2 ee0db30 => 3.1.2)
- Upgrading elvanto/litemoji (3.0.1 acd6fd9 => 3.0.1)
- Upgrading enshrined/svg-sanitize (0.15.4 e50b83a => 0.15.4)
- Upgrading ezyang/htmlpurifier (v4.14.0 12ab42b => v4.14.0)
- Upgrading guzzlehttp/guzzle (7.4.2 ac1ec1c => 7.4.2)
- Upgrading guzzlehttp/promises (1.5.1 fe752ae => 1.5.1)
- Upgrading guzzlehttp/psr7 (2.2.1 c94a94f => 2.2.1)
- Upgrading illuminate/collections (v9.9.0 03fc7ae => v9.9.0)
- Upgrading illuminate/conditionable (v9.9.0 56b4ba1 => v9.9.0)
- Upgrading illuminate/contracts (v9.9.0 de08787 => v9.9.0)
- Upgrading illuminate/macroable (v9.9.0 25a2c6d => v9.9.0)
- Upgrading justinrainbow/json-schema (5.2.12 ad87d5a => 5.2.12)
- Upgrading league/oauth2-client (2.6.1 2334c24 => 2.6.1)
- Upgrading mikehaertl/php-shellcommand (1.6.4 3488d78 => 1.6.4)
- Upgrading moneyphp/money (v4.0.3 d945f77 => v4.0.3)
- Upgrading monolog/monolog (2.5.0 4192345 => 2.5.0)
- Locking nystudio107/craft-plugin-vite (4.0.0-beta.3)
- Locking nystudio107/craft-vite (4.0.0-beta.4)
- Upgrading paragonie/random_compat (v9.99.100 996434e => v9.99.100)
- Upgrading phpdocumentor/reflection-common (2.2.0 1d01c49 => 2.2.0)
- Upgrading phpdocumentor/reflection-docblock (5.3.0 622548b => 5.3.0)
- Upgrading phpdocumentor/type-resolver (1.6.1 77a3251 => 1.6.1)
- Upgrading pixelandtonic/imagine (1.2.4.2 5ee4b6a => 1.2.4.2)
- Upgrading psr/container (2.0.2 c71ecc5 => 2.0.2)
- Upgrading psr/event-dispatcher (1.0.0 dbefd12 => 1.0.0)
- Upgrading psr/http-client (1.0.1 2dfb5f6 => 1.0.1)
- Upgrading psr/http-factory (1.0.1 12ac7fc => 1.0.1)
- Upgrading psr/http-message (1.0.1 f6561bf => 1.0.1)
- Upgrading psr/log (1.1.4 d49695b => 1.1.4)
- Upgrading psr/simple-cache (3.0.0 764e0b3 => 3.0.0)
- Upgrading ralouphie/getallheaders (3.0.3 120b605 => 3.0.3)
- Upgrading react/promise (v2.9.0 234f8fd => v2.9.0)
- Upgrading samdark/yii2-psr-log-target (1.1.3 ccb29ec => 1.1.3)
- Upgrading seld/cli-prompt (1.0.4 b8dfcf0 => 1.0.4)
- Upgrading seld/jsonlint (1.9.0 4211420 => 1.9.0)
- Upgrading seld/phar-utils (1.2.0 9f3452c => 1.2.0)
- Upgrading symfony/console (v5.4.7 9002752 => v5.4.7)
- Upgrading symfony/deprecation-contracts (v3.0.1 26954b3 => v3.0.1)
- Upgrading symfony/event-dispatcher (v6.0.3 6472ea2 => v6.0.3)
- Upgrading symfony/event-dispatcher-contracts (v3.0.1 7bc61cc => v3.0.1)
- Upgrading symfony/filesystem (v6.0.7 6c9e4c4 => v6.0.7)
- Upgrading symfony/finder (v6.0.3 8661b74 => v6.0.3)
- Upgrading symfony/http-client (v6.0.7 a7930c4 => v6.0.7)
- Upgrading symfony/http-client-contracts (v3.0.1 f752577 => v3.0.1)
- Upgrading symfony/mailer (v6.0.7 f7343f9 => v6.0.7)
- Upgrading symfony/mime (v6.0.7 74266e3 => v6.0.7)
- Upgrading symfony/polyfill-ctype (v1.25.0 3088518 => v1.25.0)
- Upgrading symfony/polyfill-iconv (v1.25.0 f1aed61 => v1.25.0)
- Upgrading symfony/polyfill-intl-grapheme (v1.25.0 81b86b5 => v1.25.0)
- Upgrading symfony/polyfill-intl-idn (v1.25.0 749045c => v1.25.0)
- Upgrading symfony/polyfill-intl-normalizer (v1.25.0 8590a5f => v1.25.0)
- Upgrading symfony/polyfill-mbstring (v1.25.0 0abb51d => v1.25.0)
- Upgrading symfony/polyfill-php72 (v1.25.0 9a14221 => v1.25.0)
- Upgrading symfony/polyfill-php73 (v1.25.0 cc5db0e => v1.25.0)
- Upgrading symfony/polyfill-php80 (v1.25.0 4407588 => v1.25.0)
- Upgrading symfony/process (v5.4.7 38a44b2 => v5.4.7)
- Upgrading symfony/service-contracts (v3.0.1 e517458 => v3.0.1)
- Upgrading symfony/string (v6.0.3 522144f => v6.0.3)
- Upgrading symfony/var-dumper (v5.4.6 294e9da => v5.4.6)
- Upgrading symfony/yaml (v5.4.3 e80f87d => v5.4.3)
- Upgrading theiconic/name-parser (v1.2.11 9a54a71 => v1.2.11)
- Upgrading true/punycode (v2.1.1 a4d0c11 => v2.1.1)
- Upgrading twig/twig (v3.3.10 8442df0 => v3.3.10)
- Upgrading voku/anti-xss (4.1.39 64a59ba => 4.1.39)
- Upgrading voku/arrayy (7.9.1 11509d5 => 7.9.1)
- Upgrading voku/email-check (3.1.0 6ea8429 => 3.1.0)
- Upgrading voku/portable-ascii (2.0.1 b56450e => 2.0.1)
- Upgrading voku/portable-utf8 (6.0.4 f6c78e4 => 6.0.4)
- Upgrading voku/stop-words (2.0.1 8e63c0a => 2.0.1)
- Upgrading voku/stringy (6.5.3 c453c88 => 6.5.3)
- Upgrading voku/urlify (5.0.7 014b207 => 5.0.7)
- Upgrading webmozart/assert (1.10.0 6964c76 => 1.10.0)
- Upgrading webonyx/graphql-php (v14.11.6 6070542 => v14.11.6)
- Upgrading yiisoft/yii2 (2.0.45 e2223d4 => 2.0.45)
- Upgrading yiisoft/yii2-composer (2.0.10 94bb3f6 => 2.0.10)
- Upgrading yiisoft/yii2-debug (2.1.19 84d20d7 => 2.1.19)
- Upgrading yiisoft/yii2-queue (2.3.4 ed30b5f => 2.3.4)
- Upgrading yiisoft/yii2-symfonymailer (2.0.3 77baddf => 2.0.3)
Writing lock file
Installing dependencies from lock file
Package operations: 2 installs, 93 updates, 3 removals
- Removing yiisoft/yii2-shell (2.0.4)
- Removing psy/psysh (v0.10.12)
- Removing nikic/php-parser (v4.13.2)
- Upgrading craftcms/plugin-installer (1.5.7 23ec472 => 1.5.7): Extracting archive
- Upgrading yiisoft/yii2-composer (2.0.10 94bb3f6 => 2.0.10): Extracting archive
- Upgrading cebe/markdown (1.2.1 9bac5e9 => 1.2.1): Extracting archive
- Upgrading doctrine/collections (1.6.8 1958a74 => 1.6.8): Extracting archive
- Upgrading commerceguys/addressing (v1.3.0 566febd => v1.3.0): Extracting archive
- Upgrading symfony/polyfill-php80 (v1.25.0 4407588 => v1.25.0): Extracting archive
- Upgrading symfony/process (v5.4.7 38a44b2 => v5.4.7): Extracting archive
- Upgrading symfony/polyfill-php73 (v1.25.0 cc5db0e => v1.25.0): Extracting archive
- Upgrading symfony/finder (v6.0.3 8661b74 => v6.0.3): Extracting archive
- Upgrading symfony/polyfill-mbstring (v1.25.0 0abb51d => v1.25.0): Extracting archive
- Upgrading symfony/polyfill-ctype (v1.25.0 3088518 => v1.25.0): Extracting archive
- Upgrading symfony/filesystem (v6.0.7 6c9e4c4 => v6.0.7): Extracting archive
- Upgrading symfony/polyfill-intl-normalizer (v1.25.0 8590a5f => v1.25.0): Extracting archive
- Upgrading symfony/polyfill-intl-grapheme (v1.25.0 81b86b5 => v1.25.0): Extracting archive
- Upgrading symfony/string (v6.0.3 522144f => v6.0.3): Extracting archive
- Upgrading psr/container (2.0.2 c71ecc5 => 2.0.2): Extracting archive
- Upgrading symfony/service-contracts (v3.0.1 e517458 => v3.0.1): Extracting archive
- Upgrading symfony/deprecation-contracts (v3.0.1 26954b3 => v3.0.1): Extracting archive
- Upgrading symfony/console (v5.4.7 9002752 => v5.4.7): Extracting archive
- Upgrading seld/phar-utils (1.2.0 9f3452c => 1.2.0): Extracting archive
- Upgrading seld/jsonlint (1.9.0 4211420 => 1.9.0): Extracting archive
- Upgrading react/promise (v2.9.0 234f8fd => v2.9.0): Extracting archive
- Upgrading psr/log (1.1.4 d49695b => 1.1.4): Extracting archive
- Upgrading justinrainbow/json-schema (5.2.12 ad87d5a => 5.2.12): Extracting archive
- Upgrading composer/pcre (3.0.0 e300eb6 => 3.0.0): Extracting archive
- Upgrading composer/xdebug-handler (3.0.3 ced2996 => 3.0.3): Extracting archive
- Upgrading composer/spdx-licenses (1.5.6 a30d487 => 1.5.6): Extracting archive
- Upgrading composer/semver (3.3.2 3953f23 => 3.3.2): Extracting archive
- Upgrading composer/metadata-minifier (1.0.0 c549d23 => 1.0.0): Extracting archive
- Upgrading composer/ca-bundle (1.3.1 4c67918 => 1.3.1): Extracting archive
- Upgrading composer/composer (2.3.5 50c47b1 => 2.3.5): Extracting archive
- Upgrading paragonie/random_compat (v9.99.100 996434e => v9.99.100): Extracting archive
- Upgrading psr/http-message (1.0.1 f6561bf => 1.0.1): Extracting archive
- Upgrading psr/http-client (1.0.1 2dfb5f6 => 1.0.1): Extracting archive
- Upgrading ralouphie/getallheaders (3.0.3 120b605 => 3.0.3): Extracting archive
- Upgrading psr/http-factory (1.0.1 12ac7fc => 1.0.1): Extracting archive
- Upgrading guzzlehttp/psr7 (2.2.1 c94a94f => 2.2.1): Extracting archive
- Upgrading guzzlehttp/promises (1.5.1 fe752ae => 1.5.1): Extracting archive
- Upgrading guzzlehttp/guzzle (7.4.2 ac1ec1c => 7.4.2): Extracting archive
- Upgrading league/oauth2-client (2.6.1 2334c24 => 2.6.1): Extracting archive
- Upgrading craftcms/oauth2-craftid (1.0.0.1 3f18364 => 1.0.0.1): Extracting archive
- Upgrading craftcms/server-check (2.1.4 c262ebd => 2.1.4): Extracting archive
- Upgrading ezyang/htmlpurifier (v4.14.0 12ab42b => v4.14.0): Extracting archive
- Upgrading yiisoft/yii2 (2.0.45 e2223d4 => 2.0.45): Extracting archive
- Upgrading symfony/polyfill-php72 (v1.25.0 9a14221 => v1.25.0): Extracting archive
- Upgrading symfony/polyfill-intl-idn (v1.25.0 749045c => v1.25.0): Extracting archive
- Upgrading symfony/mime (v6.0.7 74266e3 => v6.0.7): Extracting archive
- Upgrading psr/event-dispatcher (1.0.0 dbefd12 => 1.0.0): Extracting archive
- Upgrading symfony/event-dispatcher-contracts (v3.0.1 7bc61cc => v3.0.1): Extracting archive
- Upgrading symfony/event-dispatcher (v6.0.3 6472ea2 => v6.0.3): Extracting archive
- Upgrading doctrine/lexer (1.2.3 c268e88 => 1.2.3): Extracting archive
- Upgrading egulias/email-validator (3.1.2 ee0db30 => 3.1.2): Extracting archive
- Upgrading symfony/mailer (v6.0.7 f7343f9 => v6.0.7): Extracting archive
- Upgrading yiisoft/yii2-symfonymailer (2.0.3 77baddf => 2.0.3): Extracting archive
- Upgrading yiisoft/yii2-queue (2.3.4 ed30b5f => 2.3.4): Extracting archive
- Upgrading yiisoft/yii2-debug (2.1.19 84d20d7 => 2.1.19): Extracting archive
- Upgrading webonyx/graphql-php (v14.11.6 6070542 => v14.11.6): Extracting archive
- Upgrading voku/stop-words (2.0.1 8e63c0a => 2.0.1): Extracting archive
- Upgrading voku/portable-ascii (2.0.1 b56450e => 2.0.1): Extracting archive
- Upgrading symfony/polyfill-iconv (v1.25.0 f1aed61 => v1.25.0): Extracting archive
- Upgrading voku/portable-utf8 (6.0.4 f6c78e4 => 6.0.4): Extracting archive
- Upgrading voku/urlify (5.0.7 014b207 => 5.0.7): Extracting archive
- Upgrading voku/email-check (3.1.0 6ea8429 => 3.1.0): Extracting archive
- Upgrading webmozart/assert (1.10.0 6964c76 => 1.10.0): Extracting archive
- Upgrading phpdocumentor/reflection-common (2.2.0 1d01c49 => 2.2.0): Extracting archive
- Upgrading phpdocumentor/type-resolver (1.6.1 77a3251 => 1.6.1): Extracting archive
- Upgrading phpdocumentor/reflection-docblock (5.3.0 622548b => 5.3.0): Extracting archive
- Upgrading voku/arrayy (7.9.1 11509d5 => 7.9.1): Extracting archive
- Upgrading voku/anti-xss (4.1.39 64a59ba => 4.1.39): Extracting archive
- Upgrading defuse/php-encryption (v2.3.1 7788048 => v2.3.1): Extracting archive
- Upgrading voku/stringy (6.5.3 c453c88 => 6.5.3): Extracting archive
- Upgrading twig/twig (v3.3.10 8442df0 => v3.3.10): Extracting archive
- Upgrading true/punycode (v2.1.1 a4d0c11 => v2.1.1): Extracting archive
- Upgrading theiconic/name-parser (v1.2.11 9a54a71 => v1.2.11): Extracting archive
- Upgrading symfony/yaml (v5.4.3 e80f87d => v5.4.3): Extracting archive
- Upgrading symfony/var-dumper (v5.4.6 294e9da => v5.4.6): Extracting archive
- Upgrading symfony/http-client-contracts (v3.0.1 f752577 => v3.0.1): Extracting archive
- Upgrading symfony/http-client (v6.0.7 a7930c4 => v6.0.7): Extracting archive
- Upgrading seld/cli-prompt (1.0.4 b8dfcf0 => 1.0.4): Extracting archive
- Upgrading samdark/yii2-psr-log-target (1.1.3 ccb29ec => 1.1.3): Extracting archive
- Upgrading pixelandtonic/imagine (1.2.4.2 5ee4b6a => 1.2.4.2): Extracting archive
- Upgrading monolog/monolog (2.5.0 4192345 => 2.5.0): Extracting archive
- Upgrading moneyphp/money (v4.0.3 d945f77 => v4.0.3): Extracting archive
- Upgrading mikehaertl/php-shellcommand (1.6.4 3488d78 => 1.6.4): Extracting archive
- Upgrading illuminate/macroable (v9.9.0 25a2c6d => v9.9.0): Extracting archive
- Upgrading psr/simple-cache (3.0.0 764e0b3 => 3.0.0): Extracting archive
- Upgrading illuminate/contracts (v9.9.0 de08787 => v9.9.0): Extracting archive
- Upgrading illuminate/conditionable (v9.9.0 56b4ba1 => v9.9.0): Extracting archive
- Upgrading illuminate/collections (v9.9.0 03fc7ae => v9.9.0): Extracting archive
- Upgrading enshrined/svg-sanitize (0.15.4 e50b83a => 0.15.4): Extracting archive
- Upgrading elvanto/litemoji (3.0.1 acd6fd9 => 3.0.1): Extracting archive
- Upgrading creocoder/yii2-nested-sets (0.9.0 cb8635a => 0.9.0): Extracting archive
- Upgrading craftcms/cms (4.0.0-RC1 daac7c1 => 4.0.0-RC1): Extracting archive
- Installing nystudio107/craft-plugin-vite (4.0.0-beta.3): Extracting archive
- Installing nystudio107/craft-vite (4.0.0-beta.4): Extracting archive

Versions

  • Plugin version: 4.0.0-beta.4
  • Craft version: 4.0.0-beta@dev (also tried with ^4.0.0-alpha@dev)
  • Composer version: 2.3.5

Default config.php relies on non-standard environment variable

In the sample config.php, useDevServer is set via a DEV_MODE env variable, however pretty sure CraftCMS doesn't ship with this in .env nor does it set it by itself.

Consider replacing with App::env('ENVIRONMENT') === 'dev' which is how CraftCMS sets its devMode out of the box.

[Support] No assets output at production

My craft won't output asset links with {{ craft.vite.script("/src/app.js") }} at production.
Only the code below is output.

<script type="module">!function(){const e=document.createElement("link").relList;if(!(e&&e.supports&&e.supports("modulepreload"))){for(const e of document.querySelectorAll('link[rel="modulepreload"]'))r(e);new MutationObserver((e=>{for(const o of e)if("childList"===o.type)for(const e of o.addedNodes)if("LINK"===e.tagName&&"modulepreload"===e.rel)r(e);else if(e.querySelectorAll)for(const o of e.querySelectorAll("link[rel=modulepreload]"))r(o)})).observe(document,{childList:!0,subtree:!0})}function r(e){if(e.ep)return;e.ep=!0;const r=function(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerpolicy&&(r.referrerPolicy=e.referrerpolicy),"use-credentials"===e.crossorigin?r.credentials="include":"anonymous"===e.crossorigin?r.credentials="omit":r.credentials="same-origin",r}(e);fetch(e.href,r)}}();</script>

I couldn't figure out why but everything is fine at development mode.

craft 3.7.23
craft-vite 1.0.19

No error at debug bar at frontend.

Please help.

checkDevServer not working with vite v2.4.0

Describe the bug

With 'checkDevServer' => true, assets in src directory are not used even though vite dev server is running.
It works ok with vite v2.3.8 but not with v2.4.0 and newer version.

To reproduce

Steps to reproduce the behaviour:

  1. Set 'checkDevServer' => true
  2. Access the site while dev server running

Expected behaviour

It should reference the assets in the src directory, but instead the build assets in the dist directory.
The assets in the src directory are still accessible.

Versions

  • Plugin version: 1.0.11
  • Craft version: 3.6.17

Access blocked by CORS: domain.site <> domain.site:3000

Question

I saw this mentioned in a couple other issues here but they don't seem to have the same resolution... I've set up vite php to use the same domain for serverPublic and devServerPublic except for the addition of port 3000 in dev. And because the browser detects different ports as different origins, it throws a CORS policy error.

I was able to fix this by running:

docker exec -d ddev-router sh -c "echo 'proxy_set_header Origin \"\"; add_header \"Access-Control-Allow-Origin\" \"*\" always;' >> /etc/nginx/conf.d/default.conf"
docker exec -d ddev-router nginx -s reload

As seen in: https://github.com/mogtofu33/contenta-ddev/issues/1

But I wasn't sure if this was the right approach or if there's a better one. Do you have any insight on this? (it's currently working, so it's not a high priority, mostly reporting for documentation).

Additional context

Full CORS error:

Access to script at 'https://mydomain.ddev.site:3000/src/js/app.js' from origin 'https://mydomain.ddev.site' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Legacy plugin not compatible

Describe the bug

In vite 2.7, the name of the legacy-polyfills entry has changed from "vite/legacy-polyfills" to "\u0000vite/legacy-polyfills" which seems to be causing issues loading the legacy polyfill file.

This issue is discussed in both vitejs/vite#6097 and ElMassimo/vite_ruby#156

Versions

  • Plugin version: 1.0.15
  • Craft version: 3.7.25.1

The reason why everything is outputted from 1 line of twig code

Question

I'm struggling with splitting the output. I want only the CSS to be rendered in the <head> tags and the scripts before </body>
Is there a way to do this?

Additional context

I'm coming from TwigPack where this was possible :) I was very much intrigued by Vite.JS and it's performance so I'm investigating this plugin and setup with Nitro (no luck yet, but if the above is not possible I'm not sure this is my way to go)

Thanks!

@vite/client spotty

Describe the bug

I know this has been an issue in the past, but possibly showing up again... Vite dev server is running, and navigating to localhost:3000/src/main.ts shows the right file, but localhost:3000/@vite/client is dead, thus dev server is not being detected as running if checkDevServer => true. What makes this difficult to repro is it seems pretty spotty.

Ultimately, I don't think this is an issue with craft-vite, but with vite itself, though I wonder if there's an alternative method to dev server detection.

Versions

  • Plugin version: 4.0.0-beta.4
  • Craft version: 4.0.2
  • Vite version: 2.9.9

Mismatch of versions in .lock versus .json / Incorrect version in composer.json?

Describe the bug

I was having an issue with BuddyWorks deploying your lovely Vite plugin to a site this morning. After repeated rm -Rf cms/vendor && cms/composer.lock commands I looked in the composer.lock file to see where the mismatch was happening.

Then I saw this:

{
            "name": "nystudio107/craft-plugin-vite",
            "version": "1.0.19",
            "source": {
                "type": "git",
                "url": "https://github.com/nystudio107/craft-plugin-vite.git",
                "reference": "db53fdb759dd8f7b5716f809997630bce30719c1"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/nystudio107/craft-plugin-vite/zipball/db53fdb759dd8f7b5716f809997630bce30719c1",
                "reference": "db53fdb759dd8f7b5716f809997630bce30719c1",
                "shasum": ""
            },
            "require": {
                "craftcms/cms": "^3.0.0"
            },
            "type": "library",
            "autoload": {
                "psr-4": {
                    "nystudio107\\pluginvite\\": "src/"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "nystudio107",
                    "homepage": "https://nystudio107.com"
                }
            ],
            "description": "Plugin Vite is the conduit between Craft CMS plugins and Vite, with manifest.json & HMR support",
            "keywords": [
                "craftcms",
                "plugin",
                "vite"
            ],
            "support": {
                "docs": "https://github.com/nystudio107/craft-plugin-vite/blob/v1/README.md",
                "issues": "https://github.com/nystudio107/craft-plugin-vite/issues",
                "source": "https://github.com/nystudio107/craft-plugin-vite/tree/1.0.19"
            },
            "funding": [
                {
                    "url": "https://github.com/khalwat",
                    "type": "github"
                }
            ],
            "time": "2021-12-16T20:28:56+00:00"
        }

In my composer.json I have this:

"nystudio107/craft-vite": "1.0.20",

It also appears that there's a mismatch in how the plugin is named. I noticed this first when BuddyWorks gave me this error:

Installing dependencies from lock file
Verifying lock file contents can be installed on current platform.
Your lock file does not contain a compatible set of packages. Please run composer update.
  Problem 1
    - nystudio107/craft-vite is locked to version 1.0.20 and an update of this package was not requested.
    - You can only install one version of a package, so only one of these can be installed: nystudio107/craft-vite[1.0.20].
Action failed: see logs above for details
Container exited with status code other than 0

After looking through the composer.lock file I noticed this too:

{
            "name": "nystudio107/craft-vite",
            "version": "1.0.20",
            "source": {
                "type": "git",
                "url": "https://github.com/nystudio107/craft-vite.git",
                "reference": "b0e6c60f4d24909547b8572ddf44ab2598ce7a41"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/nystudio107/craft-vite/zipball/b0e6c60f4d24909547b8572ddf44ab2598ce7a41",
                "reference": "b0e6c60f4d24909547b8572ddf44ab2598ce7a41",
                "shasum": ""
            },
            "require": {
                "craftcms/cms": "^3.0.0",
                "nystudio107/craft-plugin-vite": "^1.0.19"
            },
            "type": "craft-plugin",
            "extra": {
                "name": "Vite",
                "handle": "vite",
                "developer": "nystudio107",
                "developerUrl": "https://nystudio107.com",
                "documentationUrl": "https://github.com/nystudio107/craft-vite/blob/master/README.md",
                "changelogUrl": "https://raw.githubusercontent.com/nystudio107/craft-vite/master/CHANGELOG.md",
                "class": "nystudio107\\vite\\Vite"
            },
            "autoload": {
                "psr-4": {
                    "nystudio107\\vite\\": "src/"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "nystudio107",
                    "homepage": "https://nystudio107.com"
                }
            ],
            "description": "Allows the use of the Vite.js next generation frontend tooling with Craft CMS",
            "keywords": [
                "Craft",
                "cms",
                "craft-plugin",
                "craftcms",
                "vite"
            ],
            "support": {
                "docs": "https://github.com/nystudio107/craft-vite/blob/master/README.md",
                "issues": "https://github.com/nystudio107/craft-vite/issues",
                "source": "https://github.com/nystudio107/craft-vite/tree/1.0.20"
            },
            "funding": [
                {
                    "url": "https://github.com/khalwat",
                    "type": "github"
                }
            ],
            "time": "2021-12-16T20:30:21+00:00"
        },

So it seems that Vite is installed twice, which is breaking our deployments. You can see from that latest json blob that craft-vite is requiring the craft-vite-plugin

Perhaps it's just because you need to update this line to the right version?

https://github.com/nystudio107/craft-vite/blob/develop/composer.json#L26

I think that may be causing the You can only install one version of a package, so only one of these can be installed: nystudio107/craft-vite[1.0.20]. issue BW is squawking about.

Expected behaviour

I'd expect that the upgrade would also update the composer.lock file appropriately as the lock file's version doesn't match what's in the main composer.json file.

Versions

  • Plugin version: 1.0.20
  • Craft version: Craft Pro 3.7.28

Thanks again for another amazing plugin!

Make errorEntry work for dd (die and dump)

Is your feature request related to a problem? Please describe.

Have to manually refresh after dying a variable to my template.

Describe the solution you would like

Have the plugin automatically inject the errorEntry into the dd screen as to refresh automatically after more changes.

Describe alternatives you have considered

I thought maybe the vite-plugin-restart or other similar ones might have this option, but it doesn't seem so.

Additional context

Nothing else to add. Thanks for all the awesome work you do!

Add to existing craft site

Question

I have an existing craft cms site that is mid development, and i would like to add vite and the vite plugin. I installed the plugin, then installed the vite and vite-plugin-restart packages.
I created a vite.php config file using your example, and created a vite.config.js file with the following:

import ViteRestart from 'vite-plugin-restart'
export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  publicDir: '',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: './src/scripts/main.js',
      },
    },
  },
  server: {
    host: '0.0.0.0',
    port: 3000,
    strictPort: true,
    https: true,
    hmr: {
      host: 'localhost',
      port: 3000,
      path: '/',
    }
  },
  plugins: [
    ViteRestart({
      reload: ['./templates/**/*'],
    }),
  ],
})

I also added the scripts commands to package.json for dev, build and preview.

My files are organised with the js/css are inside a src folder at the project root.
With this in my layouts template.
{{ craft.vite.script("/src/scripts/main.js") }}

When i run npm run dev, i get the hosts vite is running at with no errors, but i cannot get it to reload changes to the templates and src folder.

Is there something i have missed? Does a guide somewhere exist which describes how to add vite and the vite plugin to a fresh craft install rather than using your starter project?

Port 3000 now in use by DDEV

At some point in the last couple of weeks DDEV has decided to suddenly use port 3000. Not entirely sure why the change as I've not updated DDEV or Docker in that time, but I can no longer start one if the other is already running (Vite and DDEV).

Is this a 'me' thing or are others getting the same? If so and something has changed is it possible to update the docs?

Need help getting it up and running

Question

I think I followed all the steps and feel I'm really close to getting it to work. But I keep getting this error in the console:
Loading of module from 'http://localhost:8888/craft/src/ts/main.ts' is blocked due to a disallowed MIME type ('text/plain').

Any help would be much appreciated.

Additional context

file structure
Schermafbeelding 2022-06-11 om 01 07 42

vite config

export default defineConfig(({ command }) => {
  const base = (command === 'serve') ? '/craft/public_html/' : '/dist/';
  return {
    base,
    build: {
      manifest: true,
      outDir: './public_html/dist/',
      rollupOptions: {
        input: {
          app: './src/ts/main.ts',
        },
      },
    },
  };
});

plugin config

return [
    'useDevServer' => true, // App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'http://localhost:8888/craft/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => '',
    'checkDevServer' => false,
    'includeReactRefreshShim' => false,
    'includeModulePreloadShim' => true,
    'criticalPath' => '@webroot/dist/criticalcss',
    'criticalSuffix' =>'_critical.min.css',
];

index.twig

{# this evaluates to true #}
{% if craft.vite.devServerRunning() %}
  dev server is running 
 {% endif %}
{{ craft.vite.script("./src/ts/main.ts") }}

Use inside general.php

Question

I am trying to load a built css file in my general.php file. What's the PHP version of {{ craft.vite.entry("app.css") }}?

criticalUrl in .env

For the different staging areas I need to define different critical urls. Is there a way to define the critical url in an .env file?

Support React Refresh

Is your feature request related to a problem? Please describe.

Ability to use React components with HMR, currently this will error with the following during development: Uncaught Error: @vitejs/plugin-react-refresh can't detect preamble. Something is wrong.

Describe the solution you would like

Injected the following script to allow ViteJS to modify HTML via the @vitejs/plugin-react-refresh plugin (https://vitejs.dev/guide/backend-integration.html#backend-integration). Would be nice if the script respected the dev server that has been configured in vite.php config

<script type="module">
  import RefreshRuntime from 'http://localhost:3000/@react-refresh'
  RefreshRuntime.injectIntoGlobalHook(window)
  window.$RefreshReg$ = () => {}
  window.$RefreshSig$ = () => (type) => type
  window.__vite_plugin_react_preamble_installed__ = true
</script>

Describe alternatives you have considered

Currently we are manually including the above script block conditionally when in DEV mode to enable HMR of React components.

Allow styles to be included separately from scripts

Is your feature request related to a problem? Please describe.

Importing styles via Javascript causes a flash of unstyled content on every page load in development and creates difficult-to-reproduce differences in styling and animation behavior between development and production versions of the site.

Describe the solution you would like

The ability to reference styles in Twig separately from scripts, in the same way you can do in a standard, non-Craft Vite setup.

Additional context

I've been building projects with Vite outside of Craft since the very early days of Vite 2, and I almost always pull my styles into the index.html file directly vs. importing them into my Javascript. For instanceโ€ฆ

<!-- in index.html -->
<link rel='stylesheet' href='/src/styles/index.scss'>

vs.

// in index.js
import '/src/styles/index.scss';

This works perfectly, is a fully-supported behavior in Vite, and has a significant advantage over importing them in your Javascript entry file in that the injection of these styles are not blocked by Javascript and so there is no FOUC on every single page load in development. Importing in this way also does not prevent you from preprocessing your styles (you can see that I'm importing a Sass file above) and I have yet to find a single significant downside to this approach unless you are using some sort of CSS-in-JS approach which requires your styles to be imported via JS.

The FOUC content that appears on every page refresh in development isn't just annoying, it actually breaks animations and transitions that are supposed to happen immediately on page load, because those elements already exist and are rendered by the time the styles load and apply any initial state to them.

Relying on Javascript to import your styles also creates a distinct difference in behavior in development vs production, which makes it harder to troubleshoot edge-case issues around styling and animation behavior.

It would be amazing if Craft Vite would allow me to insert my styles in Twig separately from my scripts in the same way I'm able to do in a standard Vite setup.

<head>
{{ craft.vite.link("src/styles/index.scss") }}
{{ craft.vite.script("src/scripts/index.ts") }}
</head>

It looks like similar requests have been made in other issues, but none of them for the exact same reasons as mine. Hopefully this rationale makes sense.

Thank you for your hard work on bringing Vite to Craft!

[QUESTION] Using with Lalavel valet (https)

Question

Hello, I got similar issue at the below ticket.
#1 (comment)

[vite] connecting..., then [vite] server connection lost. polling for restart...

This endless repeats.
It seems to be not working with my local environment using Lalavel valet with secure option (https).
If I unsecure the site to make it to http, it works OK.

Any configuration on settings to make it work with https on valet?

Additional context

// vite.php
<?php

use craft\helpers\App;

return [
    'useDevServer' => App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'http://localhost:3000/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => '',
    'checkDevServer' => false,
];
// vite.config.js
import legacy from '@vitejs/plugin-legacy'
import ViteRestart from 'vite-plugin-restart';

export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: '/src/app.js',
      }
    },
  },
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
  ],
 server: {
    host: '0.0.0.0',
  },
});

Vite stopped working on MacOS 13.0 Ventura

Describe the bug

After updating to MacOS Ventura 13.0 I'm having issues with Vite. When running npm run serve the server starts up and I can see my latest changes. Whenever I edit a .js or .css file nothing happens, so no refresh inside the terminal and no refresh inside my browser. When i manually refresh the browser I don' see the changes.

Only when I stop my vite server and restart npm run serve I can see the changes.

To reproduce

Steps to reproduce the behaviour:

  1. Start the Vite server with npm run serve
  2. Make any changes to a file and notice how notting is being updated
  3. Close the vite server and restart it again with npm run serve
  4. Now refresh the browser and you will see the prev changes being aplied.

Expected behaviour

A clear and concise description of what you expected to happen.
Expected to see the Vite will do a reload of my changes

Versions

  • Plugin version: 4.0.3
  • Craft version: Tested on both 4.2.7 & 4.3
  • DDEV: 1.21.3

Output path to javascript files via craft.vite.entry

Question

I have a need to output the build versions of select CSS and Javascript files from a site. I have the CSS contents output with craft.vite.inline(craft.vite.entry("file.css")), but attempting to do the same for a corresponding Javascript file nets a return of just the development site base URL when craft.vite.entry("file.js") is called. The docs suggest that craft.vite.entry supports resolving a path to a built Javascript file, unless I'm misinterpreting.

Additional context

Snippet of my vite.config.js:

build: {
            emptyOutDir: false,
            manifest: true,
            outDir: './web/',
            rollupOptions: {
                input: {
                    about: '/_src/vite/about/index.ts',
                }
            },
        },

Example contents of one of the Typescript files that goes into the rollup config:

import '../scss/about.scss';

import '../js/about.js';

Thanks!

Assets loaded from primary site causing CORS error

Describe the bug

When running in production, assets are loaded with absolute URLs from the Primary site URL, not the current site.

For example:
Multisite using different domains:
sitea.com (primary)
siteb.com
sitec.com

assets on siteb.com and sitec.com will then load from sitea.com/assets/xxx causing CORS errors.

To reproduce

Create a multisite setup using different domains per site.

Expected behaviour

Assets should be loaded from the visited site domain, not from the craft assigned primary domain.

Versions

  • Vite plugin version: 1.0.16
  • Vite js version: 2.6.4
  • Craft version: 3.7.16

Using static assets and build mode

Question

Following the docs I don't really understand how the whole static assets work if they are not imported using CSS or Javascript. I use the rollup-plugin-copy as mentioned but do I also use the {{ craft.vite.asset("...") }}?

In build mode with the .env ENVIRONMENT = production it shows a (unknown) as the src of the image.

Additional context

I notice if I import the image in my app.js and console.log the image it puts the image in the manifest.json and it works. Maybe I'm missing some step of configuration here?

includeCriticalCssTags adds unwanted underscore to critical css file path

Describe the bug

We have a home template located at CRAFT_TEMPLATES_PATH/_templates/ for which we create critical css with the rollup-plugin-critical package. The generated file lies at @webroot/dist/criticalcss/home_critical.min.css.

If we want to include the file with the includeCriticalCssTags variable the file is not found because an extra underscore gets added to the file path before the template name. The path looks like this: /craft/web/dist/criticalcss/_home_critical.min.css.

The same behaviour occurs when working with templates that start with an underscore.

To reproduce

Steps to reproduce the behaviour:

  1. Create a template or template directory beginning with an underscore
  2. Build the critical css with rollup-plugin-critical
  3. Include critical css with {{ craft.vite.includeCriticalCssTags('<template>') }}
  4. See no error message and also no outputted style tag

Config files

vite.php

return [
    'useDevServer' => App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => App::env('DEV_SERVER'),
    'serverPublic' => '@web/dist/',
    'errorEntry' => 'src/js/main.js',
    'cacheKeySuffix' => '',
    'devServerInternal' => App::env('DEV_SERVER'),
    'checkDevServer' => true,
    'includeReactRefreshShim' => false,
    'includeModulePreloadShim' => true,
    'criticalPath' => '@webroot/dist/criticalcss',
    'criticalSuffix' => '_critical.min.css',
];

rollup-plugin-critical config

critical({
    criticalUrl: '<url>',
    criticalBase: '../backend/craft/web/dist/criticalcss/',
    criticalPages: [
        {uri: '', template: 'home'},
    ],
    criticalConfig: {},
}),

Versions

  • Plugin version: 1.0.28
  • Craft version: 3.7.55.2

[QUESTION] `devServerInternal` allowed me to not have to touch the config or .env file

While intentional or not, the devServerInternal config option let me set that to the Docker container running the Vite dev server and allowed me to leave useDevServer always set to 1 as it would automatically figure out if I was expecting a manifest.json or the devserver url. (I think because you were checking if the devserver responded)

This let me run the Vite dev script or the build script without any sort of .env or config file change on the Craft side.

With the removal of that setting, now I have to explicitly set useDevServer, which while manageable, means I can't just switch between a devserver or a production build locally. Maybe my desire is in the minority but figured I'd ask ๐Ÿคท๐Ÿปโ€โ™‚๏ธ

Thanks for the work on this!

400 Bad Request after starting vite dev

Question

I get a 400 Bad Request error when I open the URL http://localhost:3000 after running ddev npm run dev

docker-compose.vite.yaml

# Override the web container's standard HTTP_EXPOSE and HTTPS_EXPOSE services
# to expose port 3000 of DDEV's web container.
version: '3.6'
services:
  web:
    # ports are a list of exposed *container* ports
    ports:
      - "3000"
    environment:
      - HTTP_EXPOSE=${DDEV_ROUTER_HTTP_PORT}:80,${DDEV_MAILHOG_PORT}:8025,3001:3000
      - HTTPS_EXPOSE=${DDEV_ROUTER_HTTPS_PORT}:80,${DDEV_MAILHOG_HTTPS_PORT}:8025,3000:3000

vite.config.js
server: { host: '0.0.0.0', port: 3000, strictPort: true, },

package.json
"scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" },

Favicon support

As far as I can tell, vite-plugin-favicon is the primary solution people have to integrating favicon builds into Vite.

I see that an integration of some sort is "on the roadmap" for this Craft plugin, but I don't see any issue or documentation about it, so I am curious if that is still the case, or if it perhaps is implemented and is just lacking documentation.

I see that vite-plugin-favicon has an inject option, though there is no documentation about what happens if this is false. I noticed this pull request, though it doesn't look like it was ever merged?? Either way, I'm guessing you know something about if and how this can be integrated into a Craft setup, and would be happy to be pointed in the right direction, or even have formal support for this feature to the extent it is possible.

I guess I have 3 main questions:

  1. Is there a way to get vite-plugin-favicon to output the images and html on build to someplace where I can then include them manually?
  2. Is there a way to get vite to insert the appropriate html for favicons in development via the craft.vite.script tag
  3. If no for either of the above, do you still expect this to be supported at some point? Does it depend on the vite plugin making updates?

Having trouble getting it to work

Hi, I'm trying to get this to work, but without much result.
Here's my setup:

Craft version 3.7.8
Craft Vite plugin version 1.0.20
Local server: MAMP PRO
Local URL: http://localhost/test.com/public_html/

First question would be: after installing the Craft Vite plugin, do I need to manually install Vite.js ? Or does the plugin do this for me? (I manually installed it using npm install vite --save-dev)

Second question: do I need to manually start the Vite server? After adding the scripts dev, build and preview to the package.json I'm able to do npm run dev and Vite will start a server at http://localhost:3000/. But following that link results in an ERR_CONNECTION_REFUSED error.

Am I missing something in the docs? Or should the above simply work and am I doing something wrong?

Thanks in advance!

Can't get plugin working with DDEV - 502 Unresponsive/broken ddev back-end site.

Question

I have spent hours pouring over all the documentation I can find, tweaking parameters, but cannot seem to get my Vite server running within my DDEV environment.

I have successfully run npm run dev / vite both on local and within my container. However, any url of the form 127.0.0.1:3000/... returns a 502, as does craft.ddev.site:3000/.... This happens whether I load the url manually or through twig: {{ craft.vite.script("src/ts/index.ts") }}. The markup generated by this tag seems to be correct: <script type="module" src="https://craft.ddev.site:3000/src/ts/index.ts"></script>

Also, I have confirmed through {{ craft.vite.devServerRunning() }} that the dev server is running, though if i make 'checkDevServer' => true,, the devServerRunning tag says that it's not. So not sure what to make of that. Anyway, below are my configs - let me know if something seems off, and Thanks!

vite.php

use craft\helpers\App;

return [
    'useDevServer' => App::env('CRAFT_ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => App::env('PRIMARY_SITE_URL') . ':3000',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => 'http://localhost:3000',
    'checkDevServer' => false,
    'includeReactRefreshShim' => false,
    'includeModulePreloadShim' => true,
    // 'criticalPath' => '@webroot/dist/criticalcss',
    // 'criticalSuffix' =>'_critical.min.css',
];

vite.config.js

export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    cssCodeSplit: false,
    emptyOutDir: true,
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: './src/ts/index.ts',
      },
      output: {
        sourcemap: true,
      },
    },
  },
  plugins: [
    ViteRestart({
      restart: [
          './templates/**/*',
      ],
    }),
    mkcert(),
  ],
  server: {
    host: '0.0.0.0',
    port: 3000,
    https: true,
  },
  css: {
    postcss: postcssConfig,
  },
});

docker-compose.vite.yaml

version: '3.6'
services:
  web:
    ports:
      - '3000'
    environment:
      - HTTP_EXPOSE=${DDEV_ROUTER_HTTP_PORT}:80,${DDEV_MAILHOG_PORT}:8025,3001:3000
      - HTTPS_EXPOSE=${DDEV_ROUTER_HTTPS_PORT}:80,${DDEV_MAILHOG_HTTPS_PORT}:8025,3000:3000

src/ts/index.ts

import Alpine from 'alpinejs'
import '../css/index.css'
if (import.meta.hot) {
  import.meta.hot.accept(() => {
    console.log("HMR")
  });
}
window.Alpine = Alpine
Alpine.start()
alert('hello world')

Duplicate modulepreload links in head.

Some modulepreload link's are added twice (notice vendor in the case below) in specific manifest cases. My guess it's because of the 3 input scripts, with each slightly different imports in the js itself.

Output in html (domain redacted)

<script type="module" src="/dist/assets/main.168516cf.js" crossorigin></script>
<link href="/dist/assets/Layout.5daf469e.js" rel="modulepreload" crossorigin>
<link href="/dist/assets/vendor.01ab196e.js" rel="modulepreload" crossorigin>
<link href="/dist/assets/vendor.01ab196e.js" rel="modulepreload" crossorigin>
<link href="/dist/assets/main.575548a8.css" rel="stylesheet" media="print" onload="this.media=&#039;all&#039;">

Used manifest.json

{
  "src/js/main.js": {
    "file": "assets/main.168516cf.js",
    "src": "src/js/main.js",
    "isEntry": true,
    "imports": [
      "_Layout.5daf469e.js",
      "_vendor.01ab196e.js"
    ],
    "css": [
      "assets/main.575548a8.css"
    ],
    "assets": [
      "assets/Font-Regular.746d0c22.woff2",
      "assets/Font-Regular.1f967c79.woff",
      "assets/Font-Bold.6c627e8a.woff2",
      "assets/Font-Bold.5d3d5626.woff",
      "assets/gradient-category-cta.0cafa9fc.png",
      "assets/footer-bg.b5cbcf69.svg",
      "assets/gradient-bg-mob.7b9a948d.jpg",
      "assets/gradient-bg.d3559d31.jpg",
      "assets/home-footer-bg.3a09858a.png"
    ]
  },
  "src/js/footer.js": {
    "file": "assets/footer.1b22b364.js",
    "src": "src/js/footer.js",
    "isEntry": true,
    "css": [
      "assets/footer.f52685bf.css"
    ],
    "assets": [
      "assets/Font-Regular.746d0c22.woff2",
      "assets/Font-Regular.1f967c79.woff",
      "assets/Font-Bold.6c627e8a.woff2",
      "assets/Font-Bold.5d3d5626.woff"
    ]
  },
  "src/js/menu.js": {
    "file": "assets/menu.02571f38.js",
    "src": "src/js/menu.js",
    "isEntry": true,
    "imports": [
      "_Layout.5daf469e.js",
      "_vendor.01ab196e.js"
    ],
    "css": [
      "assets/menu.b2391e91.css"
    ],
    "assets": [
      "assets/Font-Regular.746d0c22.woff2",
      "assets/Font-Regular.1f967c79.woff",
      "assets/Font-Bold.6c627e8a.woff2",
      "assets/Font-Bold.5d3d5626.woff"
    ]
  },
  "_vendor.01ab196e.js": {
    "file": "assets/vendor.01ab196e.js"
  },
  "_Layout.5daf469e.js": {
    "file": "assets/Layout.5daf469e.js",
    "imports": [
      "_vendor.01ab196e.js"
    ]
  }
}

Versions

  • Plugin version: 1.0.16
  • Craft version: Craft Pro 3.7.16

css/pcss import issues with vite > 2.7.0

Describe the bug

Nesting a css import in a "top-level" css/pcss file loaded by an entry point fails in 2.7.0, this works as expected in 2.6.14

To reproduce

home.ts entry point:

import '@/css/app.pcss';

app.pcss:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import './components/index.pcss';
@import './overrides/index.pcss';
@import 'tailwindcss/utilities';
@import './pages/index.pcss';
@import 'vendor.pcss';

loads the app.pcss in network tab with 200 status, however in the js console:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

As we discussed in discord, I tried changing these files to use the .css extension, however this resulted in:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/css". Strict MIME type checking is enforced for module scripts per HTML spec.

Expected behaviour

no js error logged & styles to load

Versions

  • Plugin version: "nystudio107/craft-vite": "1.0.16",
  • Craft version: "craftcms/cms": "3.7.13",
  • vite: > 2.7.0

`inline()` function not working with relative local path

The craft.vite.inline() function doesn't output the contents of my CSS file when the serverPublic setting in the config uses only a relative local path and doesn't include the base URL.

Essentially, this line:

{{ craft.vite.inline(craft.vite.entry('src/scss/critical.scss')) }}

works ONLY when

'serverPublic' => App::env('BASE_URL') . '/dist/',

but NOT when

'serverPublic' => '/dist/',

craft.vite.entry('src/scss/critical.scss') outputs the correct URL in both scenarios, so it's just the inline() function that doesn't seem to be working in the latter.

There is an error output to the web log, but it's the same in both scenarios as well:

2023-01-13 16:43:03 [web.ERROR] [nystudio107\pluginvite\helpers\FileHelper::fetchResponse] cURL error 7: Failed to connect to localhost port 5173 after 1274 ms: Couldn't connect to server (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://localhost:5173/__vite_ping {"memory":1923336} 

Not a critical issue, but we would prefer to use relative paths for these resources.

Versions

  • Plugin version: 4.0.4
  • Craft version: 4.3.6.1

Suggestion: Use "expose" instead of "ports" for DDEV

Hey,

I found your example configuration for DDEV in https://nystudio107.com/docs/vite/#using-ddev while research for DDEV + vite.

Just wanted to let you know that I had a quick discussion with Randy Fay about the docker-compose file:

He suggested using expose instead of ports:

You just want expose, not ports if you're going to put it on port 3000, because with your current setup ddev-router is also going to try to use port 3000
Originally posted by rfay in torenware/ddev-viteserve#2 (comment)

(Official docs on this: https://ddev.readthedocs.io/en/stable/users/extend/custom-compose-files/#docker-composeyaml-examples, ports uses host computer, expose uses DDEV router instead)

Disclaimer: I'm not a craft dev myself, just strongly interested in vite + DDEV (https://github.com/mandrasch/ddev-addon-simple-vite).

Much success with your project and best regards,
Matthias

[an error occurred while processing the directive] printed on all pages

Describe the bug

We get the message of [an error occurred while processing the directive][an error occurred while processing the directive] printed at the the of all pages. Assets still update (HMR) fine but this message appears at the top of each page just under the opening <body> tag.

Using XDEBUG with DDEV I can see Guzzle has issues reaching the address http://localhost:3000/__vite_ping followed by the error "cURL error 7: Failed to connect to localhost port 3000: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://localhost:3000/__vite_ping"

I think this is somewhat related to #37 but I can get assets to build and update fine. Setting checkDevServer to false has no effect. It's just this message that appears.

To reproduce

Steps to reproduce the behaviour:

  1. Open any templated page.

Expected behaviour

No error at all

Versions

  • Plugin version: 1.0.28
  • Craft version: 3.7.57

ValueError: Path cannot be empty

Hi, I'm not having any luck getting craft-vite to work on my server. Locally in DDEV, it's working perfectly and the configuration is working โ€“ it will use HMR version when I set the env variable, and it will use the manifest to load built css and JS when I set it to.

On the server, it keep getting the error: ValueError: Path cannot be empty.

I suspected that it's not finding the manifest.json file, but I've even tried hard coding it and it doesn't fixe the error. I've checked the permissions on the manifest.json, and it's fine. I'm stumped -- have you see this error?

Sorry for the data dump, here's my config and stack trace. I truly appreciate any assistance or tips you can provide.

vite.php

<?php

use craft\helpers\App;

return [
    'useDevServer' => (bool) App::env('VITE_USE_DEV_SERVER'),
    'checkDevServer' => true,
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => App::env('PRIMARY_SITE_URL') . ':3000',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => 'src/js/app.js',
    'devServerInternal' => 'http://localhost:3000',
];
];

vite.config.js:

import ViteRestart from 'vite-plugin-restart';
import {defineConfig} from 'vite';
import path from 'path';
import viteCompression from 'vite-plugin-compression';
import mkcert from'vite-plugin-mkcert'

export default defineConfig(({command}) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    commonjsOptions: {
        transformMixedEsModules: true,
    },
    manifest: true,
    outDir: 'web/dist/',
    rollupOptions: {
      input: {
        app: 'src/js/global.js',
      },
      output: {
        sourcemap: true
      },
    },
  },
  plugins: [
    viteCompression({
        filter: /\.(js|mjs|json|css|map)$/i
    }),
    ViteRestart({
      reload: [
        'templates/**/*',
      ],
    }),
  ],
  publicDir: path.resolve(__dirname, 'src/public'),
  resolve: {
      alias: {
          '@': path.resolve(__dirname, 'src'),
          '@css': path.resolve(__dirname, 'src/css'),
          '@js': path.resolve(__dirname, 'src/js'),
      },
  },
  server: {
    host: '0.0.0.0',
    port: 3000,
    strictPort: true,
  }
}));

Stack Trace:

ValueError: Path cannot be empty in <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/helpers/FileHelper.php:88
Stack trace:
#0 <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/helpers/FileHelper.php(88): file_get_contents()
#1 [internal function]: nystudio107\pluginvite\helpers\FileHelper::nystudio107\pluginvite\helpers\{closure}()
#2 <my-server-info>/public_html/vendor/yiisoft/yii2/caching/Cache.php(607): call_user_func()
#3 <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/helpers/FileHelper.php(79): yii\caching\Cache->getOrSet()
#4 <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/helpers/ManifestHelper.php(54): nystudio107\pluginvite\helpers\FileHelper::fetch()
#5 <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/services/ViteService.php(455): nystudio107\pluginvite\helpers\ManifestHelper::fetchManifest()
#6 <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/services/ViteService.php(399): nystudio107\pluginvite\services\ViteService->manifestScript()
#7 <my-server-info>/public_html/vendor/nystudio107/craft-plugin-vite/src/variables/ViteVariableTrait.php(50): nystudio107\pluginvite\services\ViteService->script()
#8 <my-server-info>/public_html/vendor/twig/twig/src/Extension/CoreExtension.php(1607): nystudio107\vite\variables\ViteVariable->script()
#9 <my-server-info>/public_html/vendor/craftcms/cms/src/helpers/Template.php(101): twig_get_attribute()
#10 <my-server-info>/public_html/storage/runtime/compiled_templates/46/4613608a083214d1755c6101b69cd321.php(60): craft\helpers\Template::attribute()
#11 <my-server-info>/public_html/vendor/twig/twig/src/Template.php(394): __TwigTemplate_bb0c5fcc94d421977e1313a3f173e20c->doDisplay()
#12 <my-server-info>/public_html/vendor/twig/twig/src/Template.php(367): Twig\Template->displayWithErrorHandling()
#13 <my-server-info>/public_html/storage/runtime/compiled_templates/94/944f24e116ca9f9a1d3d4fb61237dbd5.php(48): Twig\Template->display()
#14 <my-server-info>/public_html/vendor/twig/twig/src/Template.php(394): __TwigTemplate_411e8e08f966546ad5c724cf28c02b94->doDisplay()
#15 <my-server-info>/public_html/vendor/twig/twig/src/Template.php(367): Twig\Template->displayWithErrorHandling()
#16 <my-server-info>/public_html/vendor/twig/twig/src/Template.php(379): Twig\Template->display()
#17 <my-server-info>/public_html/vendor/twig/twig/src/TemplateWrapper.php(40): Twig\Template->render()
#18 <my-server-info>/public_html/vendor/twig/twig/src/Environment.php(277): Twig\TemplateWrapper->render()
#19 <my-server-info>/public_html/vendor/craftcms/cms/src/web/View.php(428): Twig\Environment->render()
#20 <my-server-info>/public_html/vendor/craftcms/cms/src/web/View.php(481): craft\web\View->renderTemplate()
#21 <my-server-info>/public_html/vendor/craftcms/cms/src/web/TemplateResponseFormatter.php(56): craft\web\View->renderPageTemplate()
#22 <my-server-info>/public_html/vendor/yiisoft/yii2/web/Response.php(1095): craft\web\TemplateResponseFormatter->format()
#23 <my-server-info>/public_html/vendor/craftcms/cms/src/web/Response.php(286): yii\web\Response->prepare()
#24 <my-server-info>/public_html/vendor/yiisoft/yii2/web/Response.php(339): craft\web\Response->prepare()
#25 <my-server-info>/public_html/vendor/yiisoft/yii2/base/Application.php(390): yii\web\Response->send()
#26 <my-server-info>/public_html/web/index.php(12): yii\base\Application->run()
#27 {main}

.env

# The environment Craft is currently running in (dev, staging, production, etc.)
ENVIRONMENT=production

# The application ID used to to uniquely store session and cache data, mutex locks, and more
APP_ID=CraftCMS--###########

# The secure key Craft will use for hashing and encrypting data
SECURITY_KEY=###########


# The URI segment that tells Craft to load the control panel
CP_TRIGGER=admin

PRIMARY_SITE_URL=https://staging.mysite.com
BRAND_SITE_URL=https://brand.staging.mysite.com
OMNI_SITE_URL=https://portal.staging.mysite.com
VITE_USE_DEV_SERVER=0

CORS error (sitename.ddev.site <-> localhost:3000)

I followed the DDEV and Craft CMS Quick Start Guide which also covers Vite and the NYStudio107 Vite plugin. Even though the course covers Craft 3, I managed to get the Vite build working in Craft 4, but the craft.vite.script Twig tag generates a CORS error:

Access to script at 'http://localhost:3000/src/js/app.js' from origin 'https://boilerplate.ddev.site' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I can't find any support for this online, so the issue tracker is my only resort. You can view my settings in this repo or even pull the whole install. Relevant files linked below:

/.ddev/docker-compose.vite.yaml
/config/vite.php
/vite.config.js
/templates/index.twig

Any help would be much appreciated.

CriticalCSS Generation - RequestError: connect ECONNREFUSED

I'm having trouble getting CriticalCSS generated on a Nitro2 setup. When I run Vite inside my Nitro container (i.e. nitro ssh), I can successfully run build and generate my CSS, JS, manifest, and favicons. I can also get HMR working when running dev.

But I get an error when generating my CriticalCSS. It seems like it's some type of connection issue, so I've tried, rather blindly and unsuccessfully, to modify the Critical-related settings in both vite.config.js and config/vite.php.

Here's the error I get.

Generating critical CSS from http://mylittlepony.test/offices to offices/index_critical.min.css
RequestError: connect ECONNREFUSED 127.0.0.1:443
    at ClientRequest.<anonymous> (/app/node_modules/got/dist/source/core/index.js:956:111)
    at Object.onceWrapper (events.js:520:26)
    at ClientRequest.emit (events.js:412:35)
    at ClientRequest.origin.emit (/app/node_modules/@szmarczak/http-timer/dist/source/index.js:43:20)
    at TLSSocket.socketErrorListener (_http_client.js:475:9)
    at TLSSocket.emit (events.js:400:28)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16) {
  code: 'ECONNREFUSED',
  timings: {
    start: 1642638594328,
    socket: 1642638594329,
    lookup: 1642638594329,
    connect: undefined,
    secureConnect: undefined,
    upload: undefined,
    response: undefined,
    end: undefined,
    error: 1642638594330,
    abort: undefined,
    phases: {
      wait: 1,
      dns: 0,
      tcp: undefined,
      tls: undefined,
      request: undefined,
      firstByte: undefined,
      download: undefined,
      total: 2
    }
  }
}

Any guidance on what the culprit is would be much appreciated! I'm figuring I can get this working on a non-Nitro2 setup. But I can't seem to give up on Nitro2!

Running the latest version of Craft and Vite plugin. Also using the following settings:

In vite.config.js

import legacy from '@vitejs/plugin-legacy'
import ViteRestart from 'vite-plugin-restart';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import critical from 'rollup-plugin-critical';
import { ViteFaviconsPlugin } from "vite-plugin-favicon2";
import path from 'path';

export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    emptyOutDir: true,
    manifest: true,
    outDir: './web/dist/',
    rollupOptions: {
      input: {
        app: './src/js/app.js',
      }
    },
  },
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    nodeResolve({
      moduleDirectories: [
        path.resolve('./node_modules'),
      ],
    }),
    ViteRestart({
      reload: [
          './templates/**/*',
      ],
    }),
    ViteFaviconsPlugin({
      logo: "./src/img/favicon-src.png",
      inject: false,
      outputPath: 'favicons',
    }),
    critical({
      criticalUrl: 'http://mylittlepony.test/',
      criticalBase: './web/dist/criticalcss',
      criticalPages: [
        { uri: '', template: 'index' },
        { uri: 'offices', template: 'offices/index' },
      ],
      criticalConfig: {
      }
    }),
  ],
  publicDir: './src/public',
  resolve: {
    alias: {
      '@': '/src'
    }
  },
  server: {
    host: '0.0.0.0',
	 https: false,
  }
});

In config/vite.php

<?php
use craft\helpers\App;
return [

    'useDevServer' => App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'http://mylittlepony.test:3000/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '/src/js/app.js',
    'cacheKeySuffix' => '',
    'devServerInternal' => 'http://localhost:3000/',
    'checkDevServer' => true,
    'includeReactRefreshShim' => false,
    'criticalPath' => '@webroot/dist/criticalcss',
    'criticalSuffix' =>'_critical.min.css',
];

vite dev server not coming through to templates

Question

Hey, not sure if I'm doing something wrong though I cannot get vite dev server (/@vite/client.js) to come through to templates.

Additional context

As you have highlighted here, the php container cannot access the vite container on localhost:3000 so needs a different URL to check, like your comment I setup:

// VITE_DEV_SERVER_INTERNAL=http://vite:3000/
'devServerInternal' => App::env('VITE_DEV_SERVER_INTERNAL'),
    'checkDevServer' => true,

When I run xdebug, I can see content in this fetch methodhttps://github.com/nystudio107/craft-plugin-vite/blob/v1/src/services/ViteService.php#L366 it appears to be getting the contents of client.js file so it should be coming through without me needing to do anything else right?

image

Thanks for your work on this.

permissions issue

Question

I'm not sure if this is more appropriate to address here or on the Vite repo, but I am having an issue with permissions when running the build script. I am not able to build out any folders during build be it 'dist' or any other that I've tested. I am getting an EACCES: permission denied, mkdir '/web' error. Have you run into this before? Is the issue more with Vite or Rollup or my environment?

Additional context

Add any other context or screenshots about the support request here.

I am running the site locally using Laravel valet. I have created a new branch of my starter template that had previously functioned using Webpack and Mix. Running through your blog post I ran into the previously mentioned road block.

Full error:


yarn build                                                                                                                                                                                                           
yarn run v1.22.5
$ vite build
vite v2.2.4 building for production...
transforming (1) vite/dynamic-import-polyfill
warn - You have enabled the JIT engine which is currently in preview.
warn - Preview features are not covered by semver, may introduce breaking changes, and can change at any time.
โœ“ 3 modules transformed.
EACCES: permission denied, mkdir '/web'
error during build:
Error: EACCES: permission denied, mkdir '/web'
    at Object.mkdirSync (node:fs:1023:3)
    at mkdirpath (/craft3-starter/node_modules/rollup/dist/shared/rollup.js:17987:27)
    at mkdirpath (/craft3-starter/node_modules/rollup/dist/shared/rollup.js:17985:9)
    at mkdirpath (/craft3-starter/node_modules/rollup/dist/shared/rollup.js:17985:9)
    at /craft3-starter/node_modules/rollup/dist/shared/rollup.js:17998:9
    at new Promise (<anonymous>)
    at writeFile (/craft3-starter/node_modules/rollup/dist/shared/rollup.js:17997:12)
    at writeOutputFile (/craft3-starter/node_modules/rollup/dist/shared/rollup.js:20449:25)
    at /craft3-starter/node_modules/rollup/dist/shared/rollup.js:20371:65
    at Array.map (<anonymous>)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Template named "register" breaks HMR

Describe the bug

I had an issue where I had a template at the template root called register.twig and it breaks the HMR. Making changes to a css file (with a tailwind setup) breaks my HMR saying it can't find the register template. Renaming the template fixed the issue.

  • Plugin version: 4.0.3
  • Craft version: 4.3.1

CSS Link tag not rendering for craft.vite.script

Describe the bug

When I include {{ craft.vite.script(src/ts/index.ts) }} in my twig template, and dev server is not running, no <link rel="stylesheet" ...> tag is generated in my markup.

To reproduce

Steps to reproduce the behaviour:

  1. npm run build - assets and manifest are generated correctly
  2. include {{ craft.vite.script(src/ts/index.ts) }} in page template
  3. ensure dev server is not running
  4. load page containing craft.vite.script tag

Expected behaviour

scripts and styles are linked and loaded as described in docs: https://nystudio107.com/docs/vite/#production

Actual behavior

scripts are loaded and executed (no console errors), but style tag does not appear in page markup

Code Examples

The rendered head code:
image

Minimal template example:

<!DOCTYPE html>
<html lang='en'>
  <head>
    <title>{{ (pageTitle is defined ? pageTitle ~ ' - ' ~ site.siteTitle : site.siteTitle)|title }}</title>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
     {{ craft.vite.script("src/ts/index.ts", false) }}
  </head>
  <body class='flex flex-col min-h-screen'>
    {% include 'site/header'%}
    <main class='grow flex flex-col'>
      {% block main %}
      {% endblock %}
    </main>
    {% include 'site/footer' %}
  </body>
</html>

My index.ts does include an import of the css

import Alpine from 'alpinejs'
import '../css/index.css'

// Accept HMR as per: https://vitejs.dev/guide/api-hmr.html
if (import.meta.hot) {
  import.meta.hot.accept(() => {
    console.log("HMR")
  });
}

window.Alpine = Alpine
Alpine.start()

And here's my manifest.json

{
  "src/ts/index.ts": {
    "file": "assets/app.e48127f3.js",
    "src": "src/ts/index.ts",
    "isEntry": true
  },
  "style.css": {
    "file": "assets/style.92e9556c.css",
    "src": "style.css"
  }
}

Vite is generating my minified, processed css files correctly, hence why I think this is on the Plugin side.

Versions

  • Plugin version: 4.0.2
  • Craft version: 4.2.0.2

Separately output script and css tags from manifest

Is your feature request related to a problem? Please describe.

Thank you for Craft Vite ๐ŸŽ‰, it does everything absolutely by the textbook and my feature request is to achieve a slightly sub-optimal result.

Describe the solution you would like

I would like to use something like this in my twig layout:

<html>
<head>
    {% if not craft.vite.devServerRunning() %}
        {{ craft.vite.css("src/main.js", false) }}
    {% endif %}
</head>
<body>
    <div>Site here</div>

    {# Javascript #}
    {{ craft.vite.script("src/main.js") }}
</body>
</html>

This would output a link to the CSS file included from main.js in the head section and the rest of the JS loading code at the end of the site body.

Describe alternatives you have considered

Although from the docs I could use the .entry method I don't see how I can stop .script from also outputting the CSS files.

Additional context

I don't have the scope to go down a proper critical CSS setup and I want the CSS to block rendering until it loads so that there isn't a flash of unstyled content.

Is this a feature/functionality you would be open to adding? I would be more than happy to submit a PR if it is?

[Support] How to resolved static assets path imported in react components while dev server running

Question

I'm trying out craft-vite with react component.
The assets path which imported in react components are resolved fine in production build, but they aren't while dev server running.
Is there any way I can solve it?

Thanks,

Example

#app.tsx

import React, { useState } from 'react'
import logo from './logo.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Hello Vite + React!!</p>

screenshot 2021-06-10 at 17 01 00

Suggested Vite-Processed Assets path is potentially outdated

Describe the bug

Hey, hope all is good,

https://nystudio107.com/docs/vite/#vite-processed-assets suggests we need:

vite.config.js:

server: {
   origin: 'http://localhost:3000/src/', 
   host: '0.0.0.0',
}

Though with vite 2.6.14 where we have the following bg image set:

background-image:url(/src/images/marker.svg);

It gives us:

background-image: url(https://localhost:3000/src//@fs/var/www/html/src/images/marker.svg)

Looking at your docs I presume vite has changed the resulting path the dev server gives you instead with a new file-system based absolute path now.

Instead it looks like we need in vite.config.js:

origin: "https://localhost:3000",

which gives me:

background-image: url(https://localhost:3000/@fs/var/www/html/src/images/marker.svg);

(and a visible asset on the frontend)

Versions

  • Plugin version: "nystudio107/craft-vite": "1.0.16",
  • Vite version: 2.6.14
  • Craft version: "craftcms/cms": "3.7.13",

`checkDevServer` config setting not working as expected when using Vite 3

Describe the bug

The checkDevServer config setting when set to true is not having the desired effect when using it with Vite 3. Currently, when running the Vite dev server, this config setting needs to be false or not set for any assets to generate.

Similar comment here but splitting out into its own ticket.

To reproduce

Steps to reproduce the behaviour:

  1. Set checkDevServer to true in config/vite.php
  2. Run vite command
  3. In browser, no js/css assets are injected

Expected behaviour

Previous functionality with Vite 2 exists where you can set the checkDevServer setting and have the Vite Craft plugin determine whether to inject assets or read from a manifest file based on the dev server running or not.

Versions

  • Plugin version: 4.0.1
  • Craft version: 4.1.4.1
  • Vite version: 3.0

Thanks!

Include a 'devServerIsRunning' variable

As stated in your blog post, there is an issue with static assets being referenced in CSS for example (https://nystudio107.com/blog/using-vite-js-next-generation-frontend-tooling-with-craft-cms#vite-processed-assets). A workaround could be to include a <base> tag to manually set the base url for all relative links. The tag should be set to the dev server if it is running or the PRIMARY_SITE_URL if it is not.

Since this could cause other issues, the best way would be to do this manually in your templates. So what would help is a way to check if the vite dev server is running in your templates. Something like:

{% if craft.vite.devServerIsRunning %}
<base href="{{ alias('@viteBaseUrl') }}">
{% endif %}

If you would made sure that you're using absolute paths for all assets or urls in a site, then this would fix relative paths in CSS or JS.

Question about using the origin setting

Question

This is about the origin setting vite added with version 2.6.

In the docs, when talking about the origin setting, you are using devServerInternal (http://localhost:3000) as an example. This is not working for me as it throws a security error and my fonts are not being loaded (I'm serving my local site over https).

As we know, devServerPublic can run over http or https whereas devServerInternal is always http. So what I'm doing is using origin with devServerPublic instead (https://projectname.ddev.site:3000) which works fine for my use case.

Question is simple:
Is there any downside to doing this?
What's the difference between using one or the other?

Usage with Homestead

Question

Hi! I am having issues trying to run this using Homestead. When running npm run dev I can view the site, see my JS and CSS working, and in the browser console can see [vite] connecting..., then [vite] server connection lost. polling for restart..., and then finally an error WebSocket network error: The operation couldnโ€™t be completed. Connection refused. It then tries to reload and this repeats until I stop it.

As I'm running it via Homestead, do I need to use the devServerInternal and checkDevServer options? I'm not really sure what to put in there or what I'd need to configure on the Homestead VM.

My config files are below. Apologies if I'm being stupid.

Thanks! Plugin looks great and am excited to try Vite.

Additional context

// vite.php
<?php

use craft\helpers\App;

return [
    'useDevServer' => App::env('ENVIRONMENT') === 'dev',
    'manifestPath' => '@webroot/dist/manifest.json',
    'devServerPublic' => 'http://localhost:3000/',
    'serverPublic' => App::env('PRIMARY_SITE_URL') . '/dist/',
    'errorEntry' => '',
    'cacheKeySuffix' => '',
    'devServerInternal' => '',
    'checkDevServer' => false,
];
// vite.config.js
import ViteRestart from 'vite-plugin-restart';
export default ({ command }) => ({
  base: command === 'serve' ? '' : '/dist/',
  build: {
    manifest: true,
    outDir: 'craft/web/dist/',
    rollupOptions: {
      input: {
        app: 'src/js/app.js',
      }
    },
  },
  plugins: [
    ViteRestart({
      reload: [
          '/craft/templates/**/*',
      ],
    }),
  ],
});

Last Vite update breaks the site

Describe the bug

Web page now only shows

[
    'resources/js/head.js' => [
        'type' => 'file'
        'url' => 'head.efc7db5e.js'
        'options' => [
            'type' => 'module'
            'crossorigin' => true
            'onload' => 'e=new CustomEvent(\'vite-script-loaded\', {detail:{path: \'resources/js/head.js\'}});document.dispatchEvent(e);'
        ]
    ]
    'vendor.e2e1bd24.js' => [
        'crossorigin' => true
        'type' => 'import'
        'url' => 'vendor.e2e1bd24.js'
        'integrity' => ''
    ]
]

To reproduce

Steps to reproduce the behaviour:

  1. Update to last version
  2. Refresh page
  3. See error message
[
    'resources/js/head.js' => [
        'type' => 'file'
        'url' => 'head.efc7db5e.js'
        'options' => [
            'type' => 'module'
            'crossorigin' => true
            'onload' => 'e=new CustomEvent(\'vite-script-loaded\', {detail:{path: \'resources/js/head.js\'}});document.dispatchEvent(e);'
        ]
    ]
    'vendor.e2e1bd24.js' => [
        'crossorigin' => true
        'type' => 'import'
        'url' => 'vendor.e2e1bd24.js'
        'integrity' => ''
    ]
]

Expected behaviour

It doesn't break my website ๐Ÿ˜…

Screenshots

image

Versions

  • Plugin version: 1.0.22
  • Craft version: 3.7.30

Error entry does not get injected on twig error

Describe the bug

Error entry does not get injected in twig after a twig error occurs which is stopping the dev server and preventing from the page to reload after fixing the twig error.

To reproduce

Steps to reproduce the behaviour:

  1. Spin up dev server
  2. Confirm dev server is running
  3. Produce twig error
  4. Dev server stopped

Expected behaviour

After we produce a twig error, we expect the plugin to inject the errorEntry inside twig so the dev server keeps running and allowing the HMR to take place when we fix the twig error.

Screenshots

Schermafbeelding 2022-09-08 om 07 04 00

I've set the checkDevServer to false and useDevServer to true for testing purpose. Seems like the check on line 166 inside ViteService.php is always false. So the devServerRunning function is always returning false resulting in not injecting the errorEntry.

Happily to provide more info if needed.

Versions

  • Plugin version: 2.0.6
  • Craft version: 4.2.3
  • Vite version: 3.1.0
  • Vite-plugin-restart: 0.2.0

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.