### Install and Run Smallfish
Source: https://github.com/smallfishjs/smallfish/blob/master/README.md
Commands to install the package and start the development server.
```bash
$ npm install smallfish
$ smallfish dev
```
--------------------------------
### Basic GET and POST Requests with smallfish/request
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Demonstrates making basic GET and POST requests using the axios instance provided by smallfish/request. Ensure proper error handling for network requests.
```javascript
import axios from 'smallfish/request';
// Basic GET request
async function fetchUsers() {
try {
const response = await axios.get('/api/users');
return response.data;
} catch (error) {
console.error('Failed to fetch users:', error.message);
throw error;
}
}
// POST request with data
async function createUser(userData) {
const response = await axios.post('/api/users', userData, {
headers: { 'Content-Type': 'application/json' },
});
return response.data;
}
```
--------------------------------
### Execute Smallfish CLI Commands
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Use these commands for project lifecycle management including installation, development, building, and testing.
```bash
# Install smallfish
npm install smallfish
# Start development server
smallfish dev
# Build for production
smallfish build
# Run tests
smallfish test
# Run tests with coverage
smallfish cov
# Run linting checks
smallfish lint
# Run with specific port
smallfish dev --port 3000
# Extract i18n strings from source files
smallfish i18n
```
--------------------------------
### Styled Components with smallfish/styled
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Utilizes styled-components for CSS-in-JS styling in React applications. This example shows creating styled div, h2, and button components with dynamic styling based on props.
```javascript
import styled from 'smallfish/styled';
import { Button } from 'smallfish/antd';
const Container = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 24px;
`;
const Card = styled.div`
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
padding: 16px;
margin-bottom: 16px;
&:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
`;
const Title = styled.h2`
color: ${props => props.primary ? '#1890ff' : '#333'};
font-size: ${props => props.large ? '24px' : '18px'};
margin-bottom: 12px;
`;
const StyledButton = styled(Button)`
margin-right: 8px;
border-radius: 4px;
`;
export default function StyledPage() {
return (
Welcome to Smallfish
Build React applications with ease
Get StartedLearn More
);
}
```
--------------------------------
### Importing and Using Utility Libraries
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Demonstrates importing and using various utility libraries available through the smallfish/util namespace, including classnames, lodash, moment, query-string, js-cookie, uuid, and react-document-title.
```javascript
// Import utilities
import classnames from 'smallfish/util/classnames';
import debug from 'smallfish/util/debug';
import Cookies from 'smallfish/util/js-cookie';
import _ from 'smallfish/util/lodash';
import PropTypes from 'smallfish/util/prop-types';
import queryString from 'smallfish/util/query-string';
import { v4 as uuidv4 } from 'smallfish/util/uuid';
import DocumentTitle from 'smallfish/util/react-document-title';
import moment from 'smallfish/util/moment';
// Using classnames for conditional classes
const buttonClass = classnames('btn', {
'btn-primary': isPrimary,
'btn-disabled': isDisabled,
'btn-large': size === 'large',
});
// Using lodash utilities
const uniqueUsers = _.uniqBy(users, 'id');
const sortedItems = _.sortBy(items, ['priority', 'createdAt']);
const groupedData = _.groupBy(orders, 'status');
// Using moment for dates
const formattedDate = moment().format('YYYY-MM-DD HH:mm:ss');
const fromNow = moment(createdAt).fromNow();
// Using query-string
const params = queryString.parse(window.location.search);
const newUrl = queryString.stringify({ page: 1, limit: 10 });
// Using js-cookie
Cookies.set('session', sessionId, { expires: 7 });
const session = Cookies.get('session');
// Using uuid
const newId = uuidv4(); // e.g., '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// Using react-document-title
function PageWithTitle() {
return (
Page content here
);
}
```
--------------------------------
### Develop Smallfish Locally
Source: https://github.com/smallfishjs/smallfish/blob/master/README.md
Commands to bootstrap the project, build packages, and link for local development.
```bash
$ yarn
$ yarn bootstrap
$ yarn build
$ cd packages/smallfish
$ yarn link
$ cd ../../examples/func-test
$ smallfish dev
```
--------------------------------
### Configure Smallfish Project
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Define routing, plugin flags, and external resources in the config/config.js file.
```javascript
// config/config.js
export default {
// Route configuration
routes: [
{
path: '/',
component: 'IndexPage',
},
{
path: '/dashboard',
component: 'Dashboard',
routes: [
{ path: '/dashboard/overview', component: 'Overview' },
{ path: '/dashboard/settings', component: 'Settings' },
],
},
],
// Enable DVA state management
dva: true,
// Enable Ant Design Pro components
antdpro: true,
// Enable styled-components
styled: true,
// Configure i18n
i18n: {
lng: 'en',
debug: true,
keySeparator: true,
nsSeparator: true,
},
// External scripts to load
script: ['https://cdn.example.com/external-lib.js'],
// External stylesheets and inline styles
style: [
'https://cdn.example.com/external.css',
`
body {
background: #f5f5f5;
}
`,
],
};
```
--------------------------------
### Configure and Use Internationalization
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Define locale JSON files and use the i18n instance to translate strings and switch languages dynamically.
```json
// i18n/en-US.json
{
"greeting": "Hello, {{name}}!",
"items_count": "You have {{count}} items",
"date_format": "{{days}} days and {{hours}} hours remaining",
"welcome_message": "Welcome to our application"
}
```
```json
// i18n/zh-CN.json
{
"greeting": "你好, {{name}}!",
"items_count": "你有 {{count}} 个项目",
"date_format": "还剩 {{days}} 天 {{hours}} 小时",
"welcome_message": "欢迎使用我们的应用"
}
```
```javascript
// i18n/index.js - Export all locales
module.exports = {
"en-US": require("./en-US.json"),
"zh-CN": require("./zh-CN.json")
};
// page/WelcomePage/index.js - Using i18n in components
import i18n from 'smallfish/i18n';
import { Alert } from 'smallfish/antd';
export default function WelcomePage({ userName, itemCount }) {
const days = 5;
const hours = 12;
return (
{i18n.t('greeting', { name: userName })}
{i18n.t('items_count', { count: itemCount })}
{i18n.t('date_format', { days, hours })}
Current language: {i18n.language}
);
}
```
--------------------------------
### Smallfish Project Directory Structure
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Standard file and folder layout for a Smallfish project.
```text
my-project/
├── config/
│ ├── config.js # Main configuration
│ └── plugin.js # Custom plugins (optional)
├── i18n/
│ ├── index.js # Locale exports
│ ├── en-US.json # English translations
│ └── zh-CN.json # Chinese translations
├── model/
│ └── global.js # DVA models
├── page/
│ ├── IndexPage/
│ │ ├── index.js # Page component
│ │ └── index.less # Page styles
│ └── SubPage/
│ └── index.js
├── .eslintrc # ESLint config
├── .stylelintrc # Stylelint config
└── package.json
```
--------------------------------
### Utilize Ant Design Pro Components
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Leverage pre-built enterprise UI patterns like PageHeader and Result components.
```javascript
import { PageHeader, Charts, Result } from 'smallfish/ant-design-pro';
import { Button, Icon } from 'smallfish/antd';
export default function DashboardPage() {
return (
Create New Item
}
/>
Continue
}
/>
);
}
```
--------------------------------
### Custom Plugin Configuration
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Defines custom plugins and their default options in `config/plugin.js`, and then enables or configures them in `config/config.js`. This allows for extending Smallfish with custom functionality.
```javascript
// config/plugin.js
export default [
{
pluginName: 'my-custom-plugin',
configName: 'myPlugin',
defaultOptions: { enabled: true },
},
{
pluginName: 'another-plugin',
configName: 'another',
defaultOptions: false,
},
];
// config/config.js - Enable/configure plugins
export default {
myPlugin: {
enabled: true,
customOption: 'value',
},
another: true, // Enable with defaults
// Set to false to disable: myPlugin: false
};
```
--------------------------------
### Integrate Ant Design Components
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Import optimized Ant Design components directly from the framework for automatic tree-shaking.
```javascript
import { Alert, Icon, Button, Table, Form, Input, Modal } from 'smallfish/antd';
export default function UserTable({ users, onDelete }) {
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Email', dataIndex: 'email', key: 'email' },
{
title: 'Action',
key: 'action',
render: (_, record) => (
),
},
];
return (
);
}
```
--------------------------------
### Micro-Frontend Configuration with mf plugin
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Configures the micro-frontend plugin by setting the custom element tag name in `config/config.js`. This allows the application to be registered and embedded as a web component.
```javascript
// config/config.js
export default {
mf: {
tagName: 'my-app', // Must follow custom element naming (word-word)
},
// ... other config
};
// The app will be wrapped as a custom element:
//
// Can be embedded in other applications:
//
//
```
--------------------------------
### Manage State with DVA Models
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Define DVA models with effects and reducers, and connect React components to the global store using the connect HOC.
```javascript
// model/global.js - Define a DVA model
export default {
namespace: 'global',
state: {
user: null,
loading: false,
error: null,
},
effects: {
*fetchUser({ payload }, { call, put }) {
yield put({ type: 'setLoading', payload: true });
try {
const response = yield call(api.getUser, payload.userId);
yield put({ type: 'setUser', payload: response.data });
} catch (error) {
yield put({ type: 'setError', payload: error.message });
} finally {
yield put({ type: 'setLoading', payload: false });
}
},
},
reducers: {
setUser(state, { payload }) {
return { ...state, user: payload };
},
setLoading(state, { payload }) {
return { ...state, loading: payload };
},
setError(state, { payload }) {
return { ...state, error: payload };
},
},
};
// page/UserPage/index.js - Connect component to store
import { connect } from 'smallfish/dva';
import { Alert, Spin } from 'smallfish/antd';
function UserPage({ user, loading, error, dispatch }) {
const handleRefresh = () => {
dispatch({ type: 'global/fetchUser', payload: { userId: 1 } });
};
if (loading) return ;
if (error) return ;
return (
Welcome, {user?.name}
);
}
export default connect(({ global }) => ({
user: global.user,
loading: global.loading,
error: global.error,
}))(UserPage);
```
--------------------------------
### Implement Router Navigation and Guards
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Utilize React Router DOM components and HOCs for navigation, programmatic history management, and conditional route protection.
```javascript
import {
Link,
NavLink,
Redirect,
Route,
withRouter,
history,
Prompt
} from 'smallfish/router';
// Navigation component with active styling
function Navigation() {
return (
);
}
// Page component with router props via HOC
const ProfilePage = withRouter(({ match, history, location }) => {
const handleLogout = () => {
// Programmatic navigation
history.push('/login');
};
return (
User Profile: {match.params.userId}
Current path: {location.pathname}
Edit Settings
);
});
// Conditional redirect
function ProtectedRoute({ isAuthenticated, children }) {
if (!isAuthenticated) {
return ;
}
return children;
}
```
--------------------------------
### Request Interceptors with smallfish/request
Source: https://context7.com/smallfishjs/smallfish/llms.txt
Shows how to configure request and response interceptors for the axios instance. Interceptors can be used for tasks like adding authentication tokens or handling specific error codes like 401.
```javascript
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
return config;
});
axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
window.location.href = '/login';
}
return Promise.reject(error);
}
);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.