yarkov
@yarkov
Помог ответ? Отметь решением.

Как сделать динамический import * from*?

/**
 * @description Base API routes class
 * @module api/v1/BaseRoutes
 */

import * as path from 'path';

/**
 * RoutesBase class
 */
class RoutesBase {
    /**
     * @param  {Object}    config App config module instance
     * @param  {Object}    models App models module instance
     * @param  {Object}    utils  App utils module instance
     */
    constructor( config, models, utils ) {
        this.config = config;
        this.models = models;
        this.utils = utils;
    }

    /**
     * Set directory for API routes include
     *
     * @param  {String} routesdir Full path for API routes include dir
     */
    setDir( routesdir ) {
        this.routesDir = routesdir;
    }

    /**
     * Method returned API route module instance
     *
     * @param  {String}      name API route name
     *
     * @return {Object}      API route module instance
     */
    requireModule( name ) {
        const modulename = path.join( this.routesDir, name );
        // Babel ругается на строку ниже (SyntaxError: src/api/v1/BaseRoutes.js: 'import' and 'export' may only appear at the top level)
        import ModuleInstance from modulename;
        return ModuleInstance( this.config, this.models, this.utils );
        // Babel ругается на строку ниже, типа нет функции require
        // return require( modulename )( this.config, this.models, this.utils );
    }
}

export default RoutesBase;

Использую так:
class APIRoutes extends RoutesBase {
    constructor( ...args ) {
        super( ...args );
    }

    GetItems() {
        return this.requireModule( 'GetItems' );
    }
}
const routesDir = path.join( __dirname, 'inc' );
const routes = new APIRoutes( config, models, utils );

routes.setDir( routesDir );

router
    .route( '/items' )
    /**
     * Get all user items
     */
    .get( routes.GetItems() )
    .post( utils.unsupportedMethod )
    .put( utils.unsupportedMethod )
    .delete( utils.unsupportedMethod );
  • Вопрос задан
  • 575 просмотров
Пригласить эксперта
Ответы на вопрос 1
k12th
@k12th
console.log(`You're pulling my leg, right?`);
Конструкция import намеренно сделана статической, чтобы статический анализ, tree-shaking, блаблабла. Все уши прожужжали этим.

Зато недавно появился proposition dynamic import, который принимает путь, созданный в рантайме, но там придется пошаманить с Promise.all и/или async/await.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы