Skip to content
tech_e edited this page Dec 23, 2025 · 1 revision

Import - Dynamic Module Loading

Overview

The Import module enables dynamic, lazy loading of JavaScript modules and components in Base Framework. It supports code splitting, route-based loading, and dependency management to optimize application performance by loading code only when needed.

Basic Usage

Simple Import

import { Import } from '@base-framework/base';

// Import a module dynamically
Import('./components/UserProfile.js');

// Or using ES module syntax
Import(() => import('./components/UserProfile.js'));

// Or using a Promise
Import(import('./components/UserProfile.js'));

Import Patterns

String Path

// Direct path
Import('./modules/Dashboard.js');

Function (Recommended for Vite/Webpack)

// Function that returns import() - works with bundlers
Import(() => import('./modules/Dashboard.js'));

Promise

// Promise directly
Import(import('./modules/Dashboard.js'));

Configuration Object

For more control, use an object configuration:

Import({
    src: './components/UserProfile.js',
    callback: (module) => {
        console.log('Module loaded:', module);
    },
    persist: false,
    depends: [
        './styles/profile.css',
        './vendor/chart.js'
    ]
});

Configuration Options

Option Type Description
src string|function|Promise Module source path or import function
callback function Called when module loads, receives module as parameter
persist boolean Keep module loaded when parent is destroyed (default: false)
depends array Array of dependencies to load before the module
route object Route configuration for imported component

Using with Components

In Component Render

class Dashboard extends Component
{
    render()
    {
        return Div([
            H1('Dashboard'),

            // Lazy load a widget
            Import(() => import('./widgets/StatsWidget.js'))
        ]);
    }
}

Conditional Import

class Page extends Component
{
    render()
    {
        return Div([
            // Only load admin panel if user is admin
            this.isAdmin && Import(() => import('./components/AdminPanel.js'))
        ]);
    }
}

Route-Based Loading

Import components dynamically based on routes:

class App extends Component
{
    render()
    {
        return Div([
            Header(),
            {
                route: [
                    {
                        uri: '/dashboard',
                        component: Import(() => import('./pages/Dashboard.js')),
                        title: 'Dashboard'
                    },
                    {
                        uri: '/profile',
                        component: Import(() => import('./pages/Profile.js')),
                        title: 'Profile'
                    },
                    {
                        uri: '/settings',
                        component: Import(() => import('./pages/Settings.js')),
                        title: 'Settings'
                    }
                ]
            }
        ]);
    }
}

Dynamic Route Parameters

Pass route parameters to imported components:

{
    route: {
        uri: '/user/:id',
        component: Import({
            src: () => import('./pages/UserProfile.js'),
            callback: (module) => {
                console.log('User profile module loaded');
            }
        }),
        title: 'User Profile'
    }
}

Dependencies

Load CSS or other resources before the module:

Import({
    src: () => import('./components/Chart.js'),
    depends: [
        './styles/chart.css',
        './vendor/chart-library.js'
    ]
});

The module won't load until all dependencies are loaded.

Module Callbacks

Execute code when a module loads:

Import({
    src: () => import('./components/Widget.js'),
    callback: (module) => {
        console.log('Widget loaded successfully');
        console.log('Exports:', module);

        // Access module exports
        if (module.default) {
            console.log('Default export:', module.default);
        }

        // Initialize something
        module.initialize?.();
    }
});

Persistence

Non-Persistent (Default)

By default, imported modules are destroyed when their parent component is destroyed:

// Module will be unloaded when parent is destroyed
Import(() => import('./components/Temporary.js'));

Persistent Modules

Keep modules loaded even when the parent component is destroyed:

Import({
    src: () => import('./components/GlobalWidget.js'),
    persist: true  // Stays loaded
});

Use cases for persistence:

  • Global widgets
  • Shared services
  • Configuration modules
  • Analytics scripts

Module Types

Component Modules

// UserProfile.js
import { Component } from '@base-framework/base';

export class UserProfile extends Component
{
    render()
    {
        return Div({ class: 'profile' }, [
            H1('User Profile'),
            // ... profile content
        ]);
    }
}

// Or default export
export default UserProfile;

Usage:

Import(() => import('./UserProfile.js'));

Jot Component Modules

// Widget.js
import { Jot } from '@base-framework/base';

export const Widget = Jot({
    render() {
        return Div({ class: 'widget' }, 'Widget Content');
    }
});

export default Widget;

Layout Modules

// SimpleLayout.js
export default {
    class: 'simple-layout',
    children: [
        { tag: 'h1', text: 'Simple Layout' },
        { class: 'content' }
    ]
};

Advanced Patterns

Code Splitting by Feature

class App extends Component
{
    render()
    {
        return Div([
            Nav([
                NavLink({ href: '/feature1', text: 'Feature 1' }),
                NavLink({ href: '/feature2', text: 'Feature 2' }),
                NavLink({ href: '/feature3', text: 'Feature 3' })
            ]),
            {
                switch: [
                    {
                        uri: '/feature1*',
                        component: Import(() => import('./features/Feature1/index.js'))
                    },
                    {
                        uri: '/feature2*',
                        component: Import(() => import('./features/Feature2/index.js'))
                    },
                    {
                        uri: '/feature3*',
                        component: Import(() => import('./features/Feature3/index.js'))
                    }
                ]
            }
        ]);
    }
}

Lazy Load Heavy Components

class Dashboard extends Component
{
    setData()
    {
        return new Data({
            showChart: false
        });
    }

    render()
    {
        return Div([
            Button({
                text: 'Load Chart',
                click: () => this.data.set('showChart', true)
            }),
            {
                onSet: ['showChart', (show) => {
                    return show
                        ? Import(() => import('./components/HeavyChart.js'))
                        : null;
                }]
            }
        ]);
    }
}

Preload Modules

Preload modules before they're needed:

class App extends Component
{
    onCreated()
    {
        // Preload modules for faster navigation
        this.preloadModules();
    }

    preloadModules()
    {
        // Load but don't render yet
        import('./pages/Dashboard.js');
        import('./pages/Profile.js');
        import('./pages/Settings.js');
    }

    render()
    {
        return Div([
            Nav(),
            {
                route: [
                    {
                        uri: '/dashboard',
                        component: Import(() => import('./pages/Dashboard.js'))
                    },
                    {
                        uri: '/profile',
                        component: Import(() => import('./pages/Profile.js'))
                    }
                ]
            }
        ]);
    }
}

Error Boundaries

Handle import errors gracefully:

const SafeImport = (importFn) => {
    return Import({
        src: importFn,
        callback: (module) => {
            if (!module || !module.default) {
                console.error('Module failed to load properly');
                return FallbackComponent();
            }
        }
    });
};

// Usage
SafeImport(() => import('./components/MightFail.js'));

Conditional Feature Loading

Load features based on user permissions or environment:

class AdminDashboard extends Component
{
    constructor(props)
    {
        super(props);
        this.user = props.user;
    }

    render()
    {
        return Div([
            // Only admins see this
            this.user.role === 'admin' && Import(() => import('./admin/AdminTools.js')),

            // Only in development
            process.env.NODE_ENV === 'development' && Import(() => import('./dev/DevTools.js')),

            // Feature flag
            this.user.features.includes('beta') && Import(() => import('./beta/BetaFeature.js'))
        ]);
    }
}

Module Loading States

Track module loading status:

class LazyComponent extends Component
{
    setData()
    {
        return new Data({
            loading: true,
            error: false
        });
    }

    render()
    {
        return Div([
            {
                onSet: ['loading', (loading) => {
                    return loading ? Div('Loading module...') : null;
                }]
            },
            {
                onSet: ['error', (error) => {
                    return error ? Div('Failed to load module') : null;
                }]
            },
            Import({
                src: () => import('./components/HeavyWidget.js'),
                callback: (module) => {
                    this.data.set({
                        loading: false,
                        error: !module
                    });
                }
            })
        ]);
    }
}

Integration with Bundlers

Vite

// Vite understands dynamic imports
Import(() => import('./components/MyComponent.js'));

// With glob patterns
const modules = import.meta.glob('./pages/*.js');
Object.entries(modules).forEach(([path, importFn]) => {
    Import(importFn);
});

Webpack

// Webpack magic comments for chunk naming
Import(() => import(
    /* webpackChunkName: "dashboard" */
    './pages/Dashboard.js'
));

// Prefetch for better performance
Import(() => import(
    /* webpackPrefetch: true */
    './pages/Settings.js'
));

Best Practices

1. Use Function Form for Bundlers

// ✅ Good - works with bundlers
Import(() => import('./Component.js'));

// ❌ Avoid - may not work with code splitting
Import('./Component.js');

2. Lazy Load Route Components

// ✅ Good - components load on demand
{
    route: [
        { uri: '/page1', component: Import(() => import('./Page1.js')) },
        { uri: '/page2', component: Import(() => import('./Page2.js')) }
    ]
}

// ❌ Avoid - loads all components immediately
import { Page1 } from './Page1.js';
import { Page2 } from './Page2.js';

3. Group Related Features

// ✅ Good - feature-based splitting
Import(() => import('./features/UserManagement/index.js'));

// ❌ Avoid - too granular
Import(() => import('./components/UserList.js'));
Import(() => import('./components/UserForm.js'));
Import(() => import('./components/UserDetail.js'));

4. Use Dependencies Wisely

// ✅ Good - load CSS with component
Import({
    src: () => import('./components/Chart.js'),
    depends: ['./styles/chart.css']
});

// ❌ Avoid - loading unneeded dependencies
Import({
    src: () => import('./components/SimpleButton.js'),
    depends: ['./vendor/entire-ui-library.js']  // Too heavy!
});

5. Handle Loading States

// ✅ Good - show loading feedback
{
    onSet: ['showWidget', (show) => {
        if (show) {
            return Div([
                Div({ class: 'loader' }, 'Loading...'),
                Import(() => import('./Widget.js'))
            ]);
        }
    }]
}

// ❌ Avoid - no feedback during load
{
    onSet: ['showWidget', (show) => {
        return show ? Import(() => import('./Widget.js')) : null;
    }]
}

Performance Optimization

Chunk Naming

// Name your chunks for better debugging
Import(() => import(
    /* webpackChunkName: "user-profile" */
    './pages/UserProfile.js'
));

Preload Critical Routes

class App extends Component
{
    afterSetup()
    {
        // Preload likely next routes
        requestIdleCallback(() => {
            import('./pages/Dashboard.js');
            import('./pages/Profile.js');
        });
    }
}

Monitor Bundle Sizes

Keep imported chunks small for faster loading:

  • Split large features into smaller modules
  • Use tree-shaking to eliminate unused code
  • Analyze bundle with tools like webpack-bundle-analyzer

Debugging

Import({
    src: () => import('./components/Debug.js'),
    callback: (module) => {
        console.log('Module loaded:', module);
        console.log('Exports:', Object.keys(module));
        console.log('Default:', module.default);
    }
});

Common Issues

Module Not Found

// ❌ Wrong - relative to wrong location
Import(() => import('Component.js'));

// ✅ Correct - proper relative path
Import(() => import('./components/Component.js'));

Default vs Named Exports

// Module with default export
export default class MyComponent {}

// Module with named export
export class MyComponent {}

// Both work with Import - Base handles both cases
Import(() => import('./MyComponent.js'));

Clone this wiki locally