Laravel Mix报错:Uncaught ReferenceError: ScrollMagic is not defined 求助
Hey there! Let's work through this ScrollMagic reference error—this is a super common issue when combining module bundlers (like Laravel Mix) with blade templates, so let's break down the fixes step by step.
1. Fix the Import & Global Exposure
First, let's make sure you're importing ScrollMagic correctly in your app.js and exposing it to the global scope. ES modules keep variables local by default, so if your blade template code runs in the global context, it won't see the ScrollMagic import unless you explicitly attach it to window:
// app.js // Import ScrollMagic and its GSAP plugin (required for integration) import ScrollMagic from 'scrollmagic'; import 'scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap'; // Expose ScrollMagic to the global window object so blade can access it window.ScrollMagic = ScrollMagic; // Optional: Expose GSAP too if you're using it directly in your blade template import gsap from 'gsap'; window.gsap = gsap;
If you prefer minified files, adjust the import path to scrollmagic/scrollmagic/minified/... instead.
2. Verify Script Loading Order
Your bundled app.js must load before any custom ScrollMagic code in your home.blade.php. Double-check your template structure:
<!-- Load bundled app.js FIRST --> <script src="{{ mix('js/app.js') }}"></script> <!-- THEN add your ScrollMagic/GSAP code --> <script> // Now ScrollMagic will be available here const scrollController = new ScrollMagic.Controller(); // Example animation with GSAP const scene = new ScrollMagic.Scene({ triggerElement: '#your-trigger-element', duration: 300 }) .setTween(gsap.to('#animated-element', { x: 200, duration: 1 })) .addTo(scrollController); </script>
If your custom script loads first, it'll run before ScrollMagic is imported and exposed, leading to the reference error.
3. Reinstall Dependencies (Just to Be Safe)
Even if you added the dependencies to package.json, a fresh install can fix corrupted modules or version mismatches:
npm uninstall scrollmagic gsap npm install scrollmagic gsap --save
Stick to stable versions if you run into compatibility issues—for example:
// package.json "dependencies": { "scrollmagic": "^2.0.8", "gsap": "^3.12.0" }
4. Debug to Narrow Down the Issue
Add quick console logs to pinpoint where the problem is:
- In
app.js, right after importing:console.log('ScrollMagic imported:', ScrollMagic) - In your blade script:
console.log('Window ScrollMagic:', window.ScrollMagic)
If the first log shows ScrollMagic but the second shows undefined, you forgot to expose it to window. If both are undefined, your import path is wrong or the dependency didn't install correctly.
内容的提问来源于stack exchange,提问作者Mr. Pyramid

