javascript - Laravel Mix 我无法访问我的 javascript 类

标签 javascript laravel npm webpack mixins

在我的 Laravel 项目中,我编写了一个自定义表单验证类。使用 npm run dev 编译后,我无法访问此类。

我的文件

小表单验证.js

class SmallFormValidator {
    errMsgs = {
        required: 'This field is required!',
        string: 'Not valid string.',
        ...

我的app.js

require('./bootstrap');
require('./myvendor/small-form-validator');

编译后,我在公共(public)文件夹内新创建的 app.js 文件中发现了类 SmallFormValidator 的源代码。看来他编译是对的。

在我的 Blade 模板中,我使用混合助手加载了 app.js 文件。在 Blade 模板内的 Javscript 中,我无法创建 SmallFormValidation 的实例(var sfv = new SmallFormValidation())。

我认为问题的结果是

  1. 我不处理模块导出等
  2. 或者我有一些范围问题。

有谁知道如何解决这个问题吗?

最佳答案

一个简单的解决方法是将其分配给您的全局/窗口对象。在 small-form-validation.js 中添加 window.SmallFormValidator = SmallFormValidator 以使其全局可访问。

更好的方法是使用模块导出和导入

示例

//add this add the end of the file
export default SmallFormValidator

// or to the line where you start declaring the class like so:
export default class SmallFormValidator {
  // class stuff
}

在您想要使用它的文件中,您可以像这样导入它:

// top of your file
import SmallFormValidator from '../path/to/small-form-validation'

// use it how ever you want in this file
const smallFormValidator = new SmallFormValidator()
smallFormValidator.jeKaleZus() // or any other method you have

希望这有帮助

关于javascript - Laravel Mix 我无法访问我的 javascript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65846998/

相关文章:

javascript - 当我从选择框中选择产品时,如何获取相关产品的价格?

npm - 如何使用 package.json 脚本复制具有特定文件扩展名的文件

node.js - npm 安装在多域 git 存储库上失败

php - Laravel 模型中的默认随机值

javascript - 使用 javascript 剥离标签并处理换行符

javascript - PHP 的替代品包括?

javascript - scope.$destroy 未在页面重定向时触发

laravel - 不能在 Laravel 8 中使用旧工厂

javascript - 咕噜警告 : Task "concat" not found

javascript - Angular 和 Bootstrap 的路由问题