"Uncaught ReferenceError: moment is not defined" using NPM
I installed Moment.js using npm: npm install moment. I'd now like to compile it using npm run dev to replace a version I had pulled in using a CDN until now. But I just can't import it sucessfully (Uncaught ReferenceError: moment is not defined).
This is what I tried in resources/assets/js/app.js. None of the approaches is working. The file is compiled and I can access all the other stuff it contains or references in the browser, but I always get the same error regarding Moment.js.
import moment from 'moment';
var moment = require('moment');
OK, I missed that I need to attach Moment to the window object (window.moment = require('moment')) or import it more often. I'm not sure yet what "more often" means, though: Obviously it's not always sufficient to replace <script src="..."></script> (which I had in a layout view) withimport moment from 'moment' In my case I needed to import it inside several Vue components.
What's the general rule behind this? Do imports have to be repeated in every file that relies on them?
Do imports have to be repeated in every file that relies on them?
Basically yes.
Webpack generates a closure for each file so it preserves each file scope.
If you want it to be available everywhere, either bind it to the global object (in the browser it is the window.moment = moment;), or if you are using a framework, such as Vue, make it available as a plugin or on the root element.