如何使用Laravel Mix定义全局javascript函数 [英] How to use laravel mix define global javascript function

查看:186
本文介绍了如何使用Laravel Mix定义全局javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在resources/assets/js/common/utils.js中有一个功能

I already have a function in resources/assets/js/common/utils.js

'use strict'

function test(){
   console.log('test');
}

如何将utils.js定义为全局文件并在任何地方使用? 感谢您阅读我的问题!

How can I define utils.js as a global file and to be use any where? Thanks for read my question!

推荐答案

如果需要在捆绑的JavaScript文件之外使用它,可以将其附加到window对象

If you need to use it outside of your bundled JavaScript files you can attach it to the window object

window.test = function () {
  console.log('test');
}

然后您可以在其他文件中使用,例如刀片服务器模板文件

Which you can then use in other files, such as your blade template files as

window.test();

或者如果您想在捆绑的JavaScript文件中使用它,则可以将其作为模块导入

Or if you want to use it within your bundled JavaScript files you can import it as a module

// test.js
export default function test() {
    console.log('test');
}

// other.js
import test from 'test.js';

test();

只要您按照此处所述使用Laravel Mix编译文件,文档.

这篇关于如何使用Laravel Mix定义全局javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆