如何使用Laravel Mix将自定义JS工具文件设为全局可用
utils.js Globally Accessible in Laravel via Laravel Mix Hey there! I’ve got two straightforward methods to help you make that test() function available anywhere in your Laravel project. Let’s dive in:
Method 1: Mount the Function to the window Object (Simple & Direct)
This is the easiest approach—just attach your function to the browser’s global window object so it’s accessible everywhere.
Update your
utils.jsfile
Modify your existing code to explicitly mount thetestfunction towindow:'use strict'; function test(){ console.log('test'); } // Add this line to make it global window.test = test;Ensure
utils.jsis included in your build
You have two options here:- Option A: Import it into your main JS file
Openresources/assets/js/app.jsand add this line at the top:
Then your regular Laravel Mix build command (import './common/utils.js';npm run dev/prod) will bundle it intoapp.js. - Option B: Bundle it as a separate file
Update yourwebpack.mix.jsto includeutils.jsdirectly:
Don’t forget to add the generatedmix.js('resources/assets/js/app.js', 'public/js') .js('resources/assets/js/common/utils.js', 'public/js');utils.jsscript tag to your layout file (likeresources/views/layouts/app.blade.php):<script src="{{ mix('js/utils.js') }}"></script>
- Option A: Import it into your main JS file
Once you rebuild your assets, you can call test() from any JS file or even directly in your browser’s console—it’ll work!
Method 2: Use Webpack’s ProvidePlugin (More Elegant)
If you prefer not to clutter the window object, you can use Webpack’s built-in ProvidePlugin to auto-inject your function wherever it’s referenced.
Export the function from
utils.js
First, update your file to export thetestfunction (using CommonJS or ES modules):'use strict'; function test(){ console.log('test'); } // Export the function module.exports = test; // Or for ES modules: export default test;Configure Laravel Mix to use the plugin
Openwebpack.mix.jsand add the Webpack configuration forProvidePlugin:const webpack = require('webpack'); const path = require('path'); mix.js('resources/assets/js/app.js', 'public/js') .webpackConfig({ plugins: [ new webpack.ProvidePlugin({ test: path.resolve(__dirname, 'resources/assets/js/common/utils.js') }) ] });
Now, whenever you use test() in any of your JS files, Webpack will automatically import the function from utils.js without you needing to write an import statement every time.
内容的提问来源于stack exchange,提问作者Trần Quốc Vũ

