ES6 import class - babel error

379
21 января 2017, 13:08

При импорте 2 классов в файле bootstrap.js выдает ошибку:

[JS babel error] Error
message: module "./classes/Form" not found from "E:\\apps\\laravel-project.dev\\vendor\\wendenisenko\\laracms\\src\\resources\\assets\\js\\fake_fc854ebe.js"

Файл bootstrap.js я использую в скрипте 401.js. Вот мое дерево проекта:

401.js

require('./includes/bootstrap'); 
 
let 
    LoginForm = new Form($('#login-form')), 
    $systemMessage = $('#system-message'); 
 
LoginForm.ajaxSubmit({ 
    systemErrors: $systemMessage, 
    events: { 
        success: function (res){ 
            removeClass($systemMessage, 'danger'); 
            addClass($systemMessage, 'success'); 
            removeClass($systemMessage, 'hide'); 
            $systemMessage.innerHTML = res.response.data; 
            location.reload(); 
        } 
    } 
});

bootstrap.js

// import VanillaModal from 'vanilla-modal'; 
 
export function $(selector){ 
    return selector.charAt(0) == '#' ? document.getElementById(selector.slice(1)) : document.querySelectorAll(selector); 
}; 
 
export function hasClass(el, classNames){ 
    if(!el) return false; 
    return el.classList ? el.classList.contains(classNames) : new RegExp('(^| )' + classNames + '( |$)', 'gi').test(el.className); 
}; 
 
export function addClass(el, className){ 
    if(!el) return false; 
    return el.classList ? el.classList.add(className) : el.className += ' ' + className; 
}; 
 
export function removeClass(el, className){ 
    if(!el) return false; 
    return el.classList ? el.classList.remove(className) : el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); 
}; 
 
export function serializeArray(arr, name='') { 
    let arrayStr = ''; 
 
    for (let key in arr) { 
        if(arrayStr) arrayStr += '&'; 
        if(typeof arr[key] == 'object') arrayStr += serializeArray(arr[key], key); 
        else arrayStr += (name||key) + (name?'['+key+']':'')+'=' + encodeURIComponent(arr[key]); 
    } 
 
    return arrayStr; 
}; 
 
export function extend(out) { 
    out = out || {}; 
 
    for (let i = 1; i < arguments.length; i++) { 
        if (!arguments[i]) continue; 
 
        for (let key in arguments[i]) { 
            if (arguments[i].hasOwnProperty(key)) 
                out[key] = arguments[i][key]; 
        } 
    } 
 
    return out; 
}; 
 
export function extendRecursive(out) { 
    out = out || {}; 
 
    for (let i = 1; i < arguments.length; i++) { 
        let obj = arguments[i]; 
 
        if (!obj) continue; 
 
        for (let key in obj) { 
            if (obj.hasOwnProperty(key)) { 
                typeof obj[key] === 'object' ? out[key] = extendRecursive(out[key], obj[key]) : out[key] = obj[key]; 
            } 
        } 
    } 
 
    return out; 
}; 
 
import './classes/Form'; 
import './classes/Ajax';

Ajax.js

export default class Ajax { 
    constructor(config) { 
        this.request = new XMLHttpRequest(); 
        this.request.open(config.type || 'GET', config.url || '', !config.async); 
 
        if (config.dataType) this.request.responseType = config.dataType; 
 
        this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 
        if (config.data.hasOwnProperty('_token')) { 
            this.request.setRequestHeader('X-CSRF-TOKEN', config.data._token); 
            delete config.data._token; 
        } 
        if (config.headers) { 
            for (let key in config.headers) { 
                this.request.setRequestHeader(key, config.headers[key]); 
            } 
        } 
 
        let $body = $('body'); 
 
        if (config.complete) this.request.onload = function () { 
            removeClass($body, 'ajax'); 
            config.complete(this); 
        }; 
 
        if (config.error) this.request.onerror = function () { 
            removeClass($body, 'ajax'); 
            config.error(this); 
        }; 
 
        let data = config.data || null; 
        if (typeof config.data == 'object') data = serializeArray(data); 
 
        addClass($body, 'ajax'); 
        return this.request.send(data); 
    } 
}

Form.js

export default class Form { 
    constructor(el){ 
        this.form = el; 
    } 
 
    reset(){ 
        [].forEach.call(this.form.querySelectorAll('input, textarea'), function(input){ 
            input.value = null; 
        }); 
    } 
 
    disabled(status){ 
        status ? addClass(this.form, 'disabled') : removeClass(this.form, 'disabled'); 
        [].forEach.call(this.form.querySelectorAll('input, textarea, button'), function(input){ 
            status ? input.setAttribute('disabled', 'disabled') : input.removeAttribute('disabled'); 
        }); 
    } 
 
    ajaxSubmit(config){ 
        let 
            _this = this, 
            settings = { 
                systemErrors: null, 
                events: { 
                    success: function(){}, 
                    invalid: function(res){ 
                        for (let name in res.response.data) { 
                            if(name == '_system'){ 
                                if(settings.systemErrors){ 
                                    removeClass(settings.systemErrors, 'hide'); 
                                    settings.systemErrors.innerHTML = res.response.data._system; 
                                } 
                                continue; 
                            } 
 
                            let input = _this.form.querySelector('[name="'+name+'"]'); 
 
                            if(input){ 
                                addClass(input, 'input-error'); 
 
                                if(!$(':focus').length){ 
                                    input.select(); 
                                } 
 
                                // Create text element if it not exist 
                                if(!hasClass(input.nextElementSibling, 'status-text')) input.insertAdjacentHTML('afterend', '<div class="status-text"/>'); 
                                input.nextElementSibling.innerText = res.response.data[name][0]; 
                            } 
                        } 
                    }, 
                    error: function(){}, 
                }, 
            }; 
 
        if(config.systemErrors) settings.systemErrors = config.systemErrors; 
        settings.events = extend(settings.events, config.events); 
 
        // Disable default HTML form validate 
        _this.form.setAttribute('novalidate', 'novalidate'); 
 
        // Submit event 
        _this.form.addEventListener('submit', function (e) { 
            // Disable default form action 
            e.preventDefault(); 
 
            if(hasClass($('body'), 'ajax')) return false; 
 
            // Lose focus on submit btn 
            $(':focus')[0].blur(); 
 
            // Get and Validate form data 
            let 
                formData = {}, 
                allow = true; 
 
            [].forEach.call(e.target.querySelectorAll('input[name], textarea[name]'), function(input){ 
                // Save input data 
                formData[input.getAttribute('name')] = input.value; 
 
                // Check 
                if(!input.value && input.getAttribute('type') != 'hidden'){ 
                    // Disallow ajax submit 
                    allow = false; 
 
                    // Show error 
                    addClass(input, 'input-error'); 
                    if(!$(':focus').length){ 
                        input.select(); 
                    } 
                }else{ 
                    removeClass(input, 'input-error'); 
 
                    // Remove caption under input if it exists 
                    if(hasClass(input.nextElementSibling, 'status-text')) delete input.nextElementSibling.remove(); 
                } 
            }); 
 
            // Send ajax query if no errors 
            if(allow){ 
                // Disable form 
                _this.disabled(true); 
 
                // Hide header container for system messages 
                addClass(settings.systemErrors, 'hide'); 
 
                let request = new Ajax({ 
                    type: _this.form.getAttribute('method'), 
                    url: _this.form.getAttribute('action'), 
                    data: formData, 
                    dataType: 'json', 
                    complete: function(res){ 
                        // Enable form 
                        _this.disabled(false); 
 
                        if(res.statusText == 'OK'){ 
                            if(typeof res.response == 'object'){ 
                                if(settings.events[res.response.status]) return settings.events[res.response.status](res); 
                            }else console.error('Server error:\n\n'+res.response); 
                        }else console.error('Query error #'+res.status); 
                    } 
                }); 
            } 
        }); 
    } 
}

Мой gulpfile.js

var 
    gulp = require('gulp'), 
 
    // Preprocessors 
    compass = require('gulp-compass'), 
    babel = require('gulp-babel'), 
    browserify = require('gulp-browserify'), 
    babelify = require('babelify'), 
 
    // Error notifications 
    gutil = require('gulp-util'), 
 
    // AutoReloader 
    browserSync = require('browser-sync').create(), 
 
    // For production 
    cache = require('gulp-cache'), 
    tinify = require('gulp-tinify'), 
    imagemin = require('gulp-imagemin'), 
    pngquant = require('imagemin-pngquant'), 
    imageminSvgo = require('imagemin-svgo'), 
    autoprefixer = require('gulp-autoprefixer'), 
    cssmin = require('gulp-cssmin'), 
    uncss = require('gulp-uncss'), 
    uglify = require('gulp-uglify'); 
 
 
var 
    host        = 'laravel-project.dev', // For LiveReloader 
    tinifyKey   = 'dhJ4qLr3yi_Zjmpa8WGxGO31EaSaVdGj', // For tinify (image image optimization) 
    path = { 
        'source': { 
            'js':    'resources/assets/js', 
            'sass':  'resources/assets/sass', 
            'img':   'public/img', 
            'pages': 'resources/views' 
        }, 
        'dist':{ 
            'js':    'public/js', 
            'css':   'public/css', 
            'img':   'public/img' 
        } 
    }; 
 
// For package developing 
var argv = require('yargs').argv; 
if(argv.laracms!== undefined){ 
    var packagePath = 'vendor/wendenisenko/laracms/src'; 
 
    path = { 
        'source': { 
            'js':    packagePath + '/resources/assets/js', 
            'sass':  packagePath + '/resources/assets/sass', 
            'img':   'public/laracms/img', 
            'pages': packagePath + '/resources/views' 
        }, 
        'dist':{ 
            'js':    'public/laracms/js', 
            'css':   'public/laracms/css', 
            'img':   'public/laracms/img' 
        } 
    }; 
} 
 
// Errors events 
function JSError(err) { 
    const message = err.message || ''; 
    const errName = err.name || ''; 
    const codeFrame = err.codeFrame || ''; 
    gutil.log(gutil.colors.red.bold('[JS babel error]')+' '+ gutil.colors.bgRed(errName)); 
    gutil.log(gutil.colors.bold('message:') +' '+ message); 
    gutil.log(gutil.colors.bold('codeframe:') + '\n' + codeFrame); 
    this.emit('end'); 
} 
function StyleErrors(err) { 
    const type = err.type || ''; 
    const message = err.message || ''; 
    const extract = err.extract || []; 
    const line = err.line || ''; 
    const column = err.column || ''; 
    gutil.log(gutil.colors.red.bold('[SASS error]') +' '+ gutil.colors.bgRed(type) +' ('+ line +':'+ column +')'); 
    gutil.log(gutil.colors.bold('message:') +' '+ message); 
    gutil.log(gutil.colors.bold('codeframe:') +'\n'+ extract.join('\n')); 
    this.emit('end'); 
} 
 
// Preprocessor SASS 
gulp.task('sass', function() { 
    return gulp.src(path.source.sass+'/**/*.+(scss|sass)') 
        .pipe( 
            compass({ 
                project: __dirname, 
                style: 'expanded', 
                css: path.dist.css, 
                sass: path.source.sass, 
                javascript: path.dist.js, 
                image: path.dist.img 
            }).on('error', StyleErrors) 
        ) 
        .pipe(gulp.dest(path.dist.css)) 
        .pipe(browserSync.stream()); 
}); 
 
// Preprocessor ES6 to ES5 with `browserify` 
gulp.task('js', function() { 
    // return gulp.src(path.source.js+'/**/*.js') 
    //     .pipe( 
    //         babel({ 
    //             presets: ['es2015'] 
    //         }).on('error', JSError) 
    //     ) 
    //     .pipe(gulp.dest(path.dist.js)) 
    //     .pipe(browserSync.stream()); 
 
    return gulp.src(path.source.js+'/**/*.js') 
        .pipe(browserify({ 
            presets: ['es2015'] 
        }).on('error', JSError)) 
        .pipe(gulp.dest(path.dist.js)) 
        .pipe(browserSync.stream()); 
}); 
 
// SVG optimization 
gulp.task('svg', function() { 
    return gulp.src(path.source.img+'/**/*.svg') 
        .pipe(imagemin({ 
            interlaced: true, 
            progressive: true, 
            svgoPlugins: [{removeViewBox: false}] 
        })) 
        .pipe(gulp.dest(path.dist.img)); 
}); 
 
// LiveReload server 
gulp.task('browser-sync', function() { 
    return browserSync.init({ 
        proxy: host, 
        open: false, 
        notify: false 
    }); 
}); 
 
// AutoSave JS/SASS/SCSS and LiveReload 
gulp.task('watch', ['sass', 'js', 'browser-sync'], function() { 
    gulp.watch(path.source.sass+'/**/*.+(scss|sass)', ['sass']); 
    gulp.watch(path.source.js+'/**/*.js', ['js']); 
    gulp.watch(path.source.pages+'/**/*.php', browserSync.reload); 
}); 
 
// Optimize images, styles and js 
gulp.task('production', ['sass', 'js', 'svg'], function(){ 
    // CSS browsers prefixes 
    gulp.src(path.dist.css+'/**/*.css') 
        .pipe(uncss({ 
            html: [path.source.pages+'/**/*.+(php|html)'] 
        })) 
        .pipe(autoprefixer('last 15 version')) 
        .pipe(cssmin()) 
        .pipe(gulp.dest(path.dist.css)); 
 
    // JS optimization 
    gulp.src(path.dist.css+'/**/*.js') 
        .pipe(uglify()) 
        .pipe(gulp.dest(path.dist.css)); 
 
    // Images optimization 
    gulp.src(path.source.img+'/**/*.+(png|jpg|jpeg)') 
        .pipe(tinify(tinifyKey)) 
        .pipe(gulp.dest(path.dist.img)); 
}); 
 
gulp.task('clearcache', function () { return cache.clearAll(); }); 
 
gulp.task('default', ['watch']);

READ ALSO
Отмена return false у дочерних элементов

Отмена return false у дочерних элементов

Есть блок div, в него вложена ссылка На блоке висит функция, которая возращает return false по клику на этот блок

299
Обработка запроса удаленно по выбору select

Обработка запроса удаленно по выбору select

Друзья, помогите разобраться пожалуйста! Пытаюсь разобраться с jquery, задача следующая: при выборе марки машины из селекта, в соседнем div появляется...

287
Событие change не обрабатывает изменения в input

Событие change не обрабатывает изменения в input

Вот пример на plunker http://plnkrco/edit/w6GzeQapcsIO4vn7ZfC2?p=preview

277
Для каждого теста вывести в отдельной строке минимальный угол между стрелками в градусах в формате, приведенном в примере [требует правки]

Для каждого теста вывести в отдельной строке минимальный угол между стрелками в градусах в формате, приведенном в примере [требует правки]

Интервал углов между часовой и минутной стрелками часов от 0 до 180 градусов (включая углы в 0 и 180 градусов)Например, когда на часах 12 часов,...

281