Repository navigation
Import
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.
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'));// Direct path
Import('./modules/Dashboard.js');// Function that returns import() - works with bundlers
Import(() => import('./modules/Dashboard.js'));// Promise directly
Import(import('./modules/Dashboard.js'));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'
]
});| 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 |
class Dashboard extends Component
{
render()
{
return Div([
H1('Dashboard'),
// Lazy load a widget
Import(() => import('./widgets/StatsWidget.js'))
]);
}
}class Page extends Component
{
render()
{
return Div([
// Only load admin panel if user is admin
this.isAdmin && Import(() => import('./components/AdminPanel.js'))
]);
}
}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'
}
]
}
]);
}
}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'
}
}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.
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?.();
}
});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'));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
// 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'));// Widget.js
import { Jot } from '@base-framework/base';
export const Widget = Jot({
render() {
return Div({ class: 'widget' }, 'Widget Content');
}
});
export default Widget;// SimpleLayout.js
export default {
class: 'simple-layout',
children: [
{ tag: 'h1', text: 'Simple Layout' },
{ class: 'content' }
]
};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'))
}
]
}
]);
}
}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 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'))
}
]
}
]);
}
}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'));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'))
]);
}
}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
});
}
})
]);
}
}// 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 magic comments for chunk naming
Import(() => import(
/* webpackChunkName: "dashboard" */
'./pages/Dashboard.js'
));
// Prefetch for better performance
Import(() => import(
/* webpackPrefetch: true */
'./pages/Settings.js'
));// ✅ Good - works with bundlers
Import(() => import('./Component.js'));
// ❌ Avoid - may not work with code splitting
Import('./Component.js');// ✅ 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';// ✅ 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'));// ✅ 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!
});// ✅ 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;
}]
}// Name your chunks for better debugging
Import(() => import(
/* webpackChunkName: "user-profile" */
'./pages/UserProfile.js'
));class App extends Component
{
afterSetup()
{
// Preload likely next routes
requestIdleCallback(() => {
import('./pages/Dashboard.js');
import('./pages/Profile.js');
});
}
}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
Import({
src: () => import('./components/Debug.js'),
callback: (module) => {
console.log('Module loaded:', module);
console.log('Exports:', Object.keys(module));
console.log('Default:', module.default);
}
});// ❌ Wrong - relative to wrong location
Import(() => import('Component.js'));
// ✅ Correct - proper relative path
Import(() => import('./components/Component.js'));// 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'));