How to use npm package with laravel vite?

Member

by orpha , in category: PHP Frameworks , 11 days ago

How to use npm package with laravel vite?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 11 days ago

@orpha 

To use an NPM package with Laravel Vite, you can follow these steps:

  1. Install the NPM package using the following command in your Laravel project directory:
1
npm install package-name


  1. Import the NPM package into your Vite configuration file (vite.config.js). You can do this by adding an alias for the package in the resolve section of your Vite configuration file. For example, if you want to use the package "lodash", you can add the following code to your vite.config.js file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      'lodash-es': 'lodash'
    }
  }
});


  1. Now you can use the NPM package in your Laravel project by importing it into your Vue components or JavaScript files. For example, you can import the lodash package in your Vue component as follows:
1
2
3
4
5
6
7
import _ from 'lodash';

export default {
  created() {
    console.log(_.sortBy([3, 1, 2])); // Output: [1, 2, 3]
  }
}


By following these steps, you can easily use NPM packages with Laravel Vite in your projects.