Laravel-Mix编译JS文件时冗余代码及函数未定义问题求助
Hey there! Let's break down why your Laravel Mix build is spitting out extra code and making your hello() function uncallable. I've run into these exact headaches before, so here's what's going on and how to fix it:
Why Your hello() Function Is "Undefined"
The biggest culprit here is webpack's module scoping. By default, any functions or variables you define in your JS file get wrapped inside a module closure—they don't automatically attach to the global window object, so the browser can't find them when you try to call hello() directly.
Quick Fixes:
- Explicitly attach to
window:
Update your script to expose the function globally:// resources/js/your-script.js window.hello = function() { console.log("Hello from Laravel Mix!"); }; - Configure a global namespace (cleaner approach):
If you have multiple functions to expose, set up a dedicated namespace in yourwebpack.mix.js:
Now you can call your function asmix.js('resources/js/your-script.js', 'public/js', { output: { library: 'MyApp', // Your custom global namespace libraryTarget: 'window' // Attach the namespace to window } });MyApp.hello()—no messy global variable pollution!
Why You're Seeing Redundant Code
That extra code is almost always one of these scenarios:
- Dev-mode debugging tools: When you run
npm run dev, Laravel Mix (and webpack) includes source maps, runtime helpers, and unminified code to make debugging easier. For a stripped-down, production-ready build, runnpm run prodinstead—it will compress, minify, and strip out all that extra noise. - Default polyfills: Laravel Mix automatically includes Babel polyfills to support older browsers. If your app targets modern browsers only, you can disable these to slim down your build:
// webpack.mix.js mix.babelConfig({ presets: [ ['@babel/preset-env', { targets: 'defaults', useBuiltIns: false, // Disable auto polyfill inclusion corejs: false }] ] }); - Accidental dependencies: Double-check your entry script—if you're importing libraries or files you don't actually need, they'll bloat your build. Trim those unnecessary imports!
About That "Weird" Laracasts Solution
I remember seeing some hacky workarounds there (like manually tweaking webpack's raw output config), but the fixes above are the standard, maintainable approaches. The core issue is almost always module scoping and dev-mode build defaults—no need for weird hacks once you understand what's happening.
内容的提问来源于stack exchange,提问作者cbloss793

