Saturday, January 22, 2022

[FIXED] Laravel + Flatpicker: How to Install using NPM

Issue

Did is what I did so far

  1. npm i flatpickr --save
  2. Add @import "~flatpickr/dist/flatpickr.css"; to the app.scss
  3. index.blade.php
@section('content')
<div class="form-group">
<label for="loaned">Loaned</label>
<input type="date" class="form-control" name="loaned" id="loaned">
</div>
@endsection

@section('scripts')
    <script>
        flatpickr('#loaned')
    </script>
@endsection

I get an error, "flatpickr is not defined". I read the documentation but it, I don't know what to do with this part:

// commonjs
const flatpickr = require("flatpickr");

// es modules are recommended, if available, especially for typescript
import flatpickr from "flatpickr";

Solution

You can add do this in one of two ways:

In your app.js (usually under the resources folder):

import flatpckr from 'flatpickr';
window.flatpckr = flatpckr;

This will expose the flatpckr function in your global window object.

An alternative is to add all your script code in your script files instead of in the blade files e.g.:

import flatpckr from 'flatpickr';

// Maybe add conditions on when to run this
flatpckr('#loaned');

This way you don't "pollute" your window object with a bunch of libraries without needing to.



Answered By - apokryfos

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.