Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

longestdrive's avatar

Importing js library into app.js and making it available outside the module

Hi. I have a project set up using Laravel 10 that in turn uses vite. I'm having a problem understanding the best approach to scripts for pages and importing js libraries such as moment or dayjs.

After installing through npm I have updated my app.js to import the library:

import './bootstrap';
import 'laravel-datatables-vite';
import dayjs from 'dayjs';

import Alpine from 'alpinejs';
import focus from '@alpinejs/focus';

window.Alpine = Alpine;

Alpine.plugin(focus);

Alpine.start();

app.js is loaded via the page. However when I try and access dayjs from within a script tag within the page I get an error: dayjs is not defined.

This then means that the import is not being made available to scripts outside of app.js I think. In which case how best do I ensure dayjs is available outside of the module?

I have tried adding window.DayJs = dayjs; but that fails if I try to use it in the script for example:

const date = new Date();
        console.log(DayJs(date, 'd/m/Y'));

which comes up with an error DayJS is not defined

Not sure of the correct way to resolve

Thank you

0 likes
4 replies
LaryAI's avatar
Level 58

To make the imported library available outside of the module, you can attach it to the window object. In this case, you can attach dayjs to the window object by adding the following line after the import statement:

window.dayjs = dayjs;

Then, you can access dayjs from within a script tag on the page by using window.dayjs. For example:

<script>
  const date = new Date();
  console.log(window.dayjs(date).format('DD/MM/YYYY'));
</script>

This should output the formatted date to the console.

longestdrive's avatar

@LaryAI I've attached it to the window object but I still get the dayjs is not a function:

Updating app.js to:

import './bootstrap';
import 'laravel-datatables-vite';
import dayjs from 'dayjs';

import Alpine from 'alpinejs';
import focus from '@alpinejs/focus';

window.Alpine = Alpine;
window.dayjs = dayjs;

Alpine.plugin(focus);

Alpine.start();

and then trying:

console.log(window.dayjs());

The error is dayjs is not a function.

console.log(window.dayjs);

The console returns undefined

Inspecting window from within Chrome I can see dayjs is attached to the window object but I'm unable to use as expected

martinbean's avatar

@longestdrive

This reply was automagically generated by our local A.I. Think of it as a one-off attempt to instantly solve your problem. It will not respond to further replies.

selajdin's avatar

Lary missed a thing I think :

<script type="module">
    console.log(dayjs);
</script>

Please or to participate in this conversation.