You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel项目中如何在内联JavaScript中使用Webpack模块

Fixing Inline Script Access to Webpack Modules in Laravel Mix

Hey there! Let's tackle this issue where your inline <script> can't access modules like bootstrap-datepicker after switching to Laravel Mix and Webpack. I'll walk through why this happens, plus share better practices than quick workarounds (since you mentioned you already found a solution, these should help you optimize it).

Why This Happens

When you use Webpack (via Laravel Mix), modules are wrapped in their own isolated scope by default — they don't automatically leak into the global window object. In your old setup, loading scripts directly with <script> tags executed them in the global scope, so bootstrap-datepicker could attach itself to the global $/jQuery automatically. With Webpack, that auto-attachment doesn't always work unless you explicitly configure it.

1. Migrate Inline Scripts to Modular Files (Best Practice)

The cleanest approach is to ditch inline scripts entirely and move page-specific logic into dedicated JS modules. This aligns with Webpack's modular philosophy, avoids global scope pollution, and makes your code easier to maintain.

Here's how to do it:

  • Create a page-specific JS file, e.g., resources/js/pages/datepicker-init.js:
    // Import dependencies directly in the module
    import $ from 'jquery';
    import 'bootstrap-datepicker';
    
    // Initialize the datepicker when the DOM is ready
    $(document).ready(function() {
      $('.input-daterange').datepicker({
        // Add your custom options here (e.g., format: 'yyyy-mm-dd')
      });
    });
    
  • Update your webpack.mix.js to bundle this file:
    mix.js('resources/js/app.js', 'public/js')
       .js('resources/js/pages/datepicker-init.js', 'public/js/pages')
       .extract(['jquery', 'bootstrap-datepicker', 'lodash']); // Keep your existing extract config
    
  • Use Laravel Blade's @push and @stack to load the script only on pages that need it:
    • In your page's Blade template:
      @push('scripts')
      <script src="{{ mix('/js/pages/datepicker-init.js') }}"></script>
      @endpush
      
    • In your main layout (right before </body>):
      <script src="{{ mix('/js/manifest.js') }}"></script>
      <script src="{{ mix('/js/vendor.js') }}"></script>
      <script src="{{ mix('/js/app.js') }}"></script>
      @stack('scripts')
      

2. Explicitly Attach Plugins to Global jQuery

If you need to keep inline scripts temporarily, ensure that plugins like bootstrap-datepicker are properly attached to the global jQuery object. Some older plugins expect jQuery to be available globally to attach their methods.

Update your bootstrap.js file to explicitly pass jQuery to the plugin:

window.$ = window.jQuery = require('jquery');

// Explicitly attach datepicker to the global jQuery instance
require('bootstrap-datepicker')(window.jQuery);

// Keep your other imports (lodash, bootstrap-year-calendar, etc.)
window._ = require('lodash');
require('bootstrap-year-calendar');

This forces the plugin to mount its datepicker() method onto the global $.fn prototype, making it accessible to inline scripts.

3. Expose Modules to the Global Window (Quick Fix, Less Ideal)

As a last resort, you can manually expose the required methods to window, though this defeats some of Webpack's modular benefits (global scope pollution):

In your app.js file:

import $ from 'jquery';
import 'bootstrap-datepicker';

// Expose jQuery and datepicker to the global scope
window.$ = $;
window.jQuery = $;
$.fn.datepicker = require('bootstrap-datepicker');

Then your inline script should be able to call $('.input-daterange').datepicker() without errors.

4. Ensure Inline Scripts Run After Bundled Scripts

Sometimes the issue is just timing: your inline script runs before app.js/vendor.js finishes loading. Wrap your inline code in DOMContentLoaded to wait for all scripts to load:

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
  // Check if dependencies are available first
  if (typeof $ !== 'undefined' && $.fn.datepicker) {
    $('.input-daterange').datepicker();
  }
});
</script>

Final Notes

Sticking with the modular approach (solution 1) will make your codebase more scalable and easier to debug long-term. It also plays nicely with Laravel Mix's features like code splitting and hot module replacement.

内容的提问来源于stack exchange,提问作者sakinobashi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:20:30