如何从generator-ko更新此代码以与BS4和NPM一起使用

时间:2018-10-25 16:01:24

标签: javascript knockout.js gulp gulp-babel babel-core

我正在使用此knockout generator,但我想将Bower替换为NPM。 我从头开始创建了一个新应用程序,我想使用其配置来捆绑我的应用程序(我喜欢它,因为它具有我找到的最简单的spa模板)。该生成器使用BS3,但我想应用我的BS4模板。放置完模板文件并创建了一些组件之后,我尝试执行构建,但是出现此错误:

  

ReferenceError:[BABEL] src \ app \ router.js:使用已删除的Babel 5    选项:base.modules-使用相应的模块转换插件   在plugins选项中。   查看http://babeljs.io/docs/plugins/#modules       在Logger.error(_path \ node_modules \ babel-core \ lib \ transformation \ file \ logger.js:41:11)       在OptionManager.mergeOptions(_path \ node_modules \ babel-core \ lib \ transformation \ file \ options \ option-manager.js:220:20)       在OptionManager.init(_path \ node_modules \ babel-core \ lib \ transformation \ file \ options \ option-manager.js:368:12)       在File.initOptions(_path \ node_modules \ babel-core \ lib \ transformation \ file \ index.js:212:65)       在新文件(_path \ node_modules \ babel-core \ lib \ transformation \ file \ index.js:135:24)       在Pipeline.transform(_path \ node_modules \ babel-core \ lib \ transformation \ pipeline.js:46:16)       在_path \ node_modules \ babel-core \ lib \ api \ node.js:134:18       在FSReqWrap.readFileAfterClose上(按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"
  }
}

我的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'),
    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 libs一起工作的可能性。我有一个需要使用的模板,它是基于jquery构建的。

谢谢。

0 个答案:

没有答案