Как обновить этот код из generator-ko для работы с BS4 и NPM

Я использую этот генератор нокаута, но я хочу заменить Бауэра на NPM. Я создал новое приложение с нуля, и я хочу использовать его конфигурацию для комплектации своего приложения (мне это нравится, потому что у него самый простой спа-шаблон, который я нашел). Этот генератор использует BS3, но я хочу применить мой шаблон BS4. После размещения файлов шаблонов и создания некоторых компонентов я попытался выполнить сборку, но получил эту ошибку:

ReferenceError: [BABEL] src \ app \ router.js: Использование удаленной опции Babel 5: base.modules - используйте соответствующий плагин преобразования модуля в plugins вариант. Проверьте http://babeljs.io/docs/plugins/ на Logger.error (_path\node_modules\babel-core\lib\formation\file\logger.js:41:11) в OptionManager.mergeOptions (_path\) node_modules \ babel-core \ lib \ преобразование \ файл \options\option-manager.js:220:20) в OptionManager.init (_path\node_modules\babel-core\lib\ преобразование \ файл \options\option-manager.js:368:12) в File.initOptions (_path\node_modules\babel-core\lib\translation\file\index.js:212:65) в новом файле (_path \ node_modules \ babel-core \ lib \ translation\file\index.js:135:24) в Pipeline.transform (_path\node_modules\babel-core\lib\translation\pipeline.js:46:16) в _path\node_modules\babel-core\lib\api\node.js:134:18 в FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

Я вижу, что у меня есть пакеты с разными версиями, и это вызывает перерыв, но как я могу обновить код, чтобы он работал?

генератор package.json

{
  "name": "knockout-spa",
  "version": "0.0.0",
  "devDependencies": {
    "chalk": "~0.4.0",
    "deeply": "~0.1.0",
    "event-stream": "~3.1.0",
    "gulp": "^3.6.2",
    "gulp-babel": "^5.2.1",
    "gulp-clean": "~0.2.4",
    "gulp-concat": "~2.2.0",
    "gulp-connect": "^2.2.0",
    "gulp-filter": "^3.0.1",
    "gulp-html-replace": "~1.0.0",
    "gulp-replace": "~0.2.0",
    "gulp-requirejs-bundler": "^0.1.1",
    "gulp-uglify": "~0.2.1",
    "jasmine-core": "^2.3.4",
    "karma": "^0.13.10",
    "karma-babel-preprocessor": "^5.2.2",
    "karma-chrome-launcher": "^0.2.1",
    "karma-jasmine": "^0.3.6",
    "karma-requireglobal-preprocessor": "^0.0.0",
    "karma-requirejs": "^0.2.2",
    "object-assign": "^4.0.1",
    "requirejs": "^2.1.11",
    "slash": "^2.0.0"
  }
}

генератор gulpfile

// Node modules
var fs = require('fs'),
    vm = require('vm'),
    merge = require('deeply'),
    chalk = require('chalk'),
    es = require('event-stream'),
    path = require('path'),
    url = require('url');

// Gulp and plugins
var gulp = require('gulp'),
    rjs = require('gulp-requirejs-bundler'),
    concat = require('gulp-concat'),
    clean = require('gulp-clean'),
    filter = require('gulp-filter'),
    replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    htmlreplace = require('gulp-html-replace'),
    connect = require('gulp-connect'),
    babelCore = require('babel-core'),
    babel = require('gulp-babel'),
    objectAssign = require('object-assign'),
    slash = require('slash');

// Config
var requireJsRuntimeConfig = vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;'),
    requireJsOptimizerConfig = merge(requireJsRuntimeConfig, {
        out: 'scripts.js',
        baseUrl: './src',
        name: 'app/startup',
        paths: {
            requireLib: 'bower_modules/requirejs/require'
        },
        include: [
            'requireLib',
            'components/nav-bar/nav-bar',
            'components/home-page/home',
            'text!components/about-page/about.html'
        ],
        insertRequire: ['app/startup'],
        bundles: {
            // If you want parts of the site to load on demand, remove them from the 'include' list
            // above, and group them into bundles here.
            // 'bundle-name': [ 'some/module', 'another/module' ],
            // 'another-bundle-name': [ 'yet-another-module' ]
        }
    }),
    transpilationConfig = {
        root: 'src',
        skip: ['bower_modules/**', 'app/require.config.js'],
        babelConfig: {
            modules: 'amd',
            sourceMaps: 'inline'
        }
    },
    babelIgnoreRegexes = transpilationConfig.skip.map(function (item) {
        return babelCore.util.regexify(item);
    });

// Pushes all the source files through Babel for transpilation
gulp.task('js:babel', function () {
    return gulp.src(requireJsOptimizerConfig.baseUrl + '/**')
        .pipe(es.map(function (data, cb) {
            if (!data.isNull()) {
                babelTranspile(data.relative, function (err, res) {
                    if (res) {
                        data.contents = new Buffer(res.code);
                    }
                    cb(err, data);
                });
            } else {
                cb(null, data);
            }
        }))
        .pipe(gulp.dest('./temp'));
});

// Discovers all AMD dependencies, concatenates together all required .js files, minifies them
gulp.task('js:optimize', ['js:babel'], function () {
    var config = objectAssign({}, requireJsOptimizerConfig, {
        baseUrl: 'temp'
    });
    return rjs(config)
        .pipe(uglify({
            preserveComments: 'some'
        }))
        .pipe(gulp.dest('./dist/'));
})

// Builds the distributable .js files by calling Babel then the r.js optimizer
gulp.task('js', ['js:optimize'], function () {
    // Now clean up
    return gulp.src('./temp', {
        read: false
    }).pipe(clean());
});

// Concatenates CSS files, rewrites relative paths to Bootstrap fonts, copies Bootstrap fonts
gulp.task('css', function () {
    var bowerCss = gulp.src('src/bower_modules/components-bootstrap/css/bootstrap.min.css')
        .pipe(replace(/url\((')?\.\.\/fonts\//g, 'url($1fonts/')),
        appCss = gulp.src('src/css/*.css'),
        combinedCss = es.concat(bowerCss, appCss).pipe(concat('css.css')),
        fontFiles = gulp.src('./src/bower_modules/components-bootstrap/fonts/*', {
            base: './src/bower_modules/components-bootstrap/'
        });
    return es.concat(combinedCss, fontFiles)
        .pipe(gulp.dest('./dist/'));
});

// Copies index.html, replacing <script> and <link> tags to reference production URLs
gulp.task('html', function () {
    return gulp.src('./src/index.html')
        .pipe(htmlreplace({
            'css': 'css.css',
            'js': 'scripts.js'
        }))
        .pipe(gulp.dest('./dist/'));
});

// Removes all files from ./dist/
gulp.task('clean', function () {
    return gulp.src('./dist/**/*', {
            read: false
        })
        .pipe(clean());
});

// Starts a simple static file server that transpiles ES6 on the fly to ES5
gulp.task('serve:src', function () {
    return connect.server({
        root: transpilationConfig.root,
        middleware: function (connect, opt) {
            return [
                function (req, res, next) {
                    var pathname = path.normalize(url.parse(req.url).pathname);
                    babelTranspile(pathname, function (err, result) {
                        if (err) {
                            next(err);
                        } else if (result) {
                            res.setHeader('Content-Type', 'application/javascript');
                            res.end(result.code);
                        } else {
                            next();
                        }
                    });
                }
            ];
        }
    });
});

// After building, starts a trivial static file server
gulp.task('serve:dist', ['default'], function () {
    return connect.server({
        root: './dist'
    });
});

function babelTranspile(pathname, callback) {
    pathname = slash(pathname);
    if (babelIgnoreRegexes.some(function (re) {
            return re.test(pathname);
        })) return callback();
    if (!babelCore.canCompile(pathname)) return callback();
    var src = path.join(transpilationConfig.root, pathname);
    var opts = objectAssign({
        sourceFileName: '/source/' + pathname
    }, transpilationConfig.babelConfig);
    babelCore.transformFile(src, opts, callback);
}

gulp.task('default', ['html', 'js', 'css'], function (callback) {
    callback();
    console.log('\nPlaced optimized files in ' + chalk.magenta('dist/\n'));
});

генератор router.js

import ko from 'knockout';
import crossroads from 'crossroads';
import hasher from 'hasher';

// This module configures crossroads.js, a routing library. If you prefer, you
// can use any other routing library (or none at all) as Knockout is designed to
// compose cleanly with external libraries.
//
// You *don't* have to follow the pattern established here (each route entry
// specifies a 'page', which is a Knockout component) - there's nothing built into
// Knockout that requires or even knows about this technique. It's just one of
// many possible ways of setting up client-side routes.

class Router {
    constructor(config) {
        this.currentRoute = ko.observable({});

        // Configure Crossroads route handlers
        ko.utils.arrayForEach(config.routes, (route) => {
            crossroads.addRoute(route.url, (requestParams) => {
                this.currentRoute(ko.utils.extend(requestParams, route.params));
            });
        });

        // Activate Crossroads
        crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
        hasher.initialized.add(hash => crossroads.parse(hash));
        hasher.changed.add(hash => crossroads.parse(hash));
        hasher.init();
    }
}

// Create and export router instance
var routerInstance = new Router({
    routes: [
        { url: '',          params: { page: 'home-page' } },
        { url: 'about',     params: { page: 'about-page' } }
    ]
});

export default routerInstance;

Мой package.json (без каких-либо строк)

{
  "scripts": {
    "build": "gulp"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0",
    "chalk": "^2.4.1",
    "deeply": "^2.0.3",
    "event-stream": "^4.0.1",
    "fancy-log": "^1.3.2",
    "gulp": "^3.9.1",
    "gulp-babel": "^7.0.1",
    "gulp-clean": "^0.4.0",
    "gulp-concat": "^2.6.1",
    "gulp-connect": "^5.6.1",
    "gulp-filter": "^5.1.0",
    "gulp-html-replace": "^1.6.2",
    "gulp-replace": "^1.0.0",
    "gulp-requirejs-bundler": "^0.1.1",
    "gulp-uglify": "^3.0.1",
    "object-assign": "^4.1.1",
    "requirejs": "^2.3.6",
    "slash": "^2.0.0"
  },
  "dependencies": {
    "bootstrap": "^4.1.3",
    "bootstrap-table": "^1.12.1",
    "crossroads": "^0.12.2",
    "fastclick": "^1.0.6",
    "hasher": "^1.2.0",
    "jquery": "^3.3.1",
    "jquery-slimscroll": "^1.3.8",
    "jquery.nicescroll": "^3.7.6",
    "jquery.scrollto": "^2.1.2",
    "knockout": "^3.4.2",
    "ladda": "^2.0.1",
    "one-com-knockout-projections": "^1.6.0",
    "popper.js": "^1.14.4",
    "requirejs-text": "^2.0.15",
    "sammy": "^0.7.6",
    "signals": "^1.0.0",
    "summernote": "^0.8.10",
    "sweetalert2": "^7.28.10",
    "wowjs": "^1.1.3"
  }
}

Мой глоток

// Node modules
var fs = require('fs'),
    vm = require('vm'),
    merge = require('deeply'),
    chalk = require('chalk'),
    es = require('event-stream'),
    path = require('path'),
    url = require('url');


// Gulp and plugins
var gulp = require('gulp'),
    rjs = require('gulp-requirejs-bundler'),
    concat = require('gulp-concat'),
    clean = require('gulp-clean'),
    filter = require('gulp-filter'),
    replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    htmlreplace = require('gulp-html-replace'),
    connect = require('gulp-connect'),
    babelCore = require('babel-core'),
    babel = require('gulp-babel'),
    objectAssign = require('object-assign'),
    log = require('fancy-log'),
    slash = require('slash');

// Config
var requireConfig = vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;');

var optmizeConfig = merge(requireConfig, {
    out: 'scripts.js',
    baseUrl: './src',
    name: 'app/startup',
    paths: {
        requireLib: '../node_modules/requirejs/require'
    },
    include: [
        'requireLib',
        'components/nav-bar/nav-bar',
        'components/sidebar/sidebar',
        'components/rightbar/rightbar',
        'components/home-page/home',
    ],
    insertRequire: ['app/startup'],
    bundles: {
        // If you want parts of the site to load on demand, remove them from the 'include' list
        // above, and group them into bundles here.
        // 'bundle-name': [ 'some/module', 'another/module' ],
        // 'another-bundle-name': [ 'yet-another-module' ]
    }
});
var transpilationConfig = {
    root: 'src',
    skip: ['app/require.config.js'],
    babelConfig: {
        modules: 'amd',
        sourceMaps: 'inline'
    }
};
var babelIgnoreRegexes = transpilationConfig.skip.map(function (item) {
    return babelCore.util.regexify(item);
});

gulp.task('js:babel', function () {
    return gulp.src(optmizeConfig.baseUrl + '/**')
        .pipe(es.map(function (data, cb) {
            if (!data.isNull()) {
                babelTranspile(data.relative, function (err, res) {
                    if (res) {
                        data.contents = new Buffer(res.code);
                    }
                    cb(err, data);
                });
            } else {
                cb(null, data);
            }
        }))
        .pipe(gulp.dest('./temp'));
});

function babelTranspile(pathname, callback) {
    pathname = slash(pathname);
    if (babelIgnoreRegexes.some(function (re) {        log('aqui #2');        return re.test(pathname);    })) {
        return callback();
    }
    if (!babelCore.util.canCompile(pathname)) {
        return callback();
    }
    var src = path.join(transpilationConfig.root, pathname);

    var opts = objectAssign({sourceFileName: '/source/' + pathname}, transpilationConfig.babelConfig);
    // the error happens here
    babelCore.transformFile(src, opts, callback);
}

gulp.task('print', function () {
    log(babelIgnoreRegexes);
})

(в нем есть журнал, потому что я пытался найти, где происходит ошибка)

мой router.js

import ko from 'knockout';
import crossroads from 'crossroads';
import hasher from 'hasher';

class Router {
    constructor(config) {
        this.currentRoute = ko.observable({});

        // Configure Crossroads route handlers
        ko.utils.arrayForEach(config.routes, (route) => {
            crossroads.addRoute(route.url, (requestParams) => {
                this.currentRoute(ko.utils.extend(requestParams, route.params));
            });
        });

        // Activate Crossroads
        crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
        hasher.initialized.add(hash => crossroads.parse(hash));
        hasher.changed.add(hash => crossroads.parse(hash));
        hasher.init();
    }
}

//Create and export router instance
let routerInstance = new Router({
    routes: [
        { url: '',          params: { page: 'home-page' } },
        { url: 'about',     params: { page: 'about-page' } }
    ]
});

export default routerInstance;

Если в шаблоне есть плохие идеи, как я могу настроить свое приложение на хорошие? Мне нравятся идеи ленивой загрузки компонентов, которые приносит генератор, простота нокаута и возможность работать с библиотеками jquery и jquery. И у меня есть шаблон, который мне нужно использовать, который построен на jquery.

Благодарю.

0 ответов

Другие вопросы по тегам