{"id":15414,"library":"build-plugin-ice-request","title":"Ice.js Request Configuration Plugin","description":"build-plugin-ice-request is a core plugin for the Ice.js (now often `@ice/app`) framework, designed to standardize and enhance network request handling within Ice.js applications. It facilitates global configuration of HTTP requests, leveraging an Axios-compatible interface. This includes setting up base URLs, timeouts, and defining request and response interceptors for global error handling, authentication, and data transformation. The plugin integrates deeply into the Ice.js runtime, exposing `request` (imperative) and `useRequest` (React hook) APIs for components to interact with the configured request service. The current stable version is `2.0.1`, with updates and compatibility closely tied to the frequent release cycle of the `@ice/app` framework (e.g., v3.x series). Its primary differentiator is its seamless integration into the Ice.js build and runtime, providing a consistent and configurable request layer across the application.","status":"active","version":"2.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/alibaba/ice/tree/master/packages/plugin-request","tags":["javascript"],"install":[{"cmd":"npm install build-plugin-ice-request","lang":"bash","label":"npm"},{"cmd":"yarn add build-plugin-ice-request","lang":"bash","label":"yarn"},{"cmd":"pnpm add build-plugin-ice-request","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The `request` utility is exposed by the main 'ice' package after the plugin is configured, not directly from the plugin package.","wrong":"import { request } from 'build-plugin-ice-request'","symbol":"request","correct":"import { request } from 'ice'"},{"note":"The `useRequest` hook is provided by the main 'ice' package for use in React components, not directly from the plugin package.","wrong":"import { useRequest } from 'build-plugin-ice-request'","symbol":"useRequest","correct":"import { useRequest } from 'ice'"},{"note":"Ice.js applications are primarily ESM-first. Use ES Modules imports for `runApp` and other core utilities.","wrong":"const { runApp } = require('ice')","symbol":"runApp","correct":"import { runApp } from 'ice'"},{"note":"`defineConfig` for application-level configuration typically comes from `@ice/app`.","wrong":"import { defineConfig } from 'ice'","symbol":"defineConfig","correct":"import { defineConfig } from '@ice/app'"}],"quickstart":{"code":"// build.json (or similar build configuration file)\n// Make sure to add the plugin to your Ice.js build configuration.\n// For older Ice.js versions, this is often in build.json:\n/*\n{\n  \"plugins\": [\n    \"build-plugin-ice-request\"\n  ]\n}\n*/\n\n// src/app.ts (or src/index.ts - global application entry point)\nimport { runApp, request, useRequest } from 'ice';\nimport React, { useEffect } from 'react';\n\n// Configure the global request service within your Ice.js application\nconst appConfig = {\n  request: {\n    baseURL: '/api', // Example: All requests will be prefixed with /api\n    timeout: 5000,   // Example: Request timeout of 5 seconds\n    interceptors: {\n      request: {\n        onConfig: (config) => {\n          console.log('Request interceptor (onConfig):', config.url);\n          // Example: Add an authorization token to all requests\n          const token = localStorage.getItem('authToken');\n          if (token) {\n            config.headers = { ...config.headers, Authorization: `Bearer ${token}` };\n          }\n          return config;\n        },\n        onError: (error) => {\n          console.error('Request interceptor (onError):', error.message);\n          return Promise.reject(error);\n        }\n      },\n      response: {\n        onConfig: (response) => {\n          console.log('Response interceptor (onConfig):', response.config.url, response.status);\n          return response;\n        },\n        onError: (error) => {\n          console.error('Response interceptor (onError):', error.response?.status, error.message);\n          // Example: Handle 401 Unauthorized errors globally\n          if (error.response?.status === 401) {\n            alert('Session expired. Please log in again.');\n            // window.location.href = '/login'; // Redirect to login page\n          }\n          return Promise.reject(error);\n        }\n      }\n    }\n  }\n};\n\n// Initialize the Ice.js application with the configured request service\nrunApp(appConfig);\n\n// Example Component Usage (in a React component within your Ice.js app)\nconst DataDisplay = () => {\n  // Using the useRequest hook for automatic data fetching\n  const { loading, error, data, request: fetchData } = useRequest({\n    url: '/users',\n    method: 'GET',\n    manual: true // Set to true to manually trigger the request\n  });\n\n  useEffect(() => {\n    fetchData(); // Trigger the request on component mount\n  }, [fetchData]);\n\n  // Using the imperative request function\n  const postData = async () => {\n    try {\n      const result = await request('/posts', { method: 'POST', data: { title: 'New Post', content: '...' } });\n      console.log('Post successful:', result);\n    } catch (err) {\n      console.error('Post failed:', err);\n    }\n  };\n\n  if (loading) return <div>Loading user data...</div>;\n  if (error) return <div>Error: {error.message}</div>;\n\n  return (\n    <div>\n      <h2>Users:</h2>\n      <pre>{JSON.stringify(data, null, 2)}</pre>\n      <button onClick={postData}>Create New Post</button>\n    </div>\n  );\n};\n\nexport default DataDisplay; // Export for routing or direct use in an Ice.js app","lang":"typescript","description":"This quickstart demonstrates how to integrate `build-plugin-ice-request` into an Ice.js application, configure global request interceptors via `runApp`, and then utilize both the `useRequest` hook and the imperative `request` function within a component."},"warnings":[{"fix":"Ensure your request configuration is structured under `appConfig.request` in your application's entry file (e.g., `src/app.ts` or `src/index.ts`).","message":"The global request configuration, including `baseURL`, `timeout`, and `interceptors`, must be defined within the `request` property of the `appConfig` object, which is passed to `runApp`. Attempting to configure these settings directly as a plugin option in `defineConfig` will not affect runtime request behavior.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always import request utilities as `import { request, useRequest } from 'ice';`.","message":"The `request` and `useRequest` functions are exposed directly from the main `ice` (or `@ice/app`) package, not from `build-plugin-ice-request`. Directly importing them from the plugin package (`import { request } from 'build-plugin-ice-request'`) will result in runtime errors.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always consult the `@ice/app` documentation for specific plugin compatibility matrices and ensure both `@ice/app` and `build-plugin-ice-request` are updated to compatible versions.","message":"While `build-plugin-ice-request` has its own versioning, its runtime behavior and API compatibility are tightly coupled with the major versions of the underlying Ice.js framework (now `@ice/app`). Using an incompatible plugin version with your framework version can lead to unexpected runtime issues or type mismatches.","severity":"breaking","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Verify that `build-plugin-ice-request` is listed in your `build.json` (or equivalent Ice.js plugin configuration) and that `runApp` includes a `request` configuration block. Ensure `import { request } from 'ice';` is used.","cause":"The `build-plugin-ice-request` is not correctly configured or enabled in the build system, or `request` is imported from the wrong package.","error":"TypeError: (0 , ice__WEBPACK_IMPORTED_MODULE_1__.request) is not a function"},{"fix":"Update `@ice/app` and any related `@types` packages (e.g., `@types/ice`) to match your framework version. If using a custom type, ensure it extends or includes the `request` property.","cause":"TypeScript type definition mismatch, indicating either an outdated `@types/ice` package or a custom `AppConfig` interface that doesn't include the `request` property.","error":"Property 'request' does not exist on type 'AppConfig'"},{"error":"Network Error"},{"error":"AxiosError: Request failed with status code 404"},{"fix":"Review the `baseURL` in `appConfig.request` and the relative paths used in `request()` calls. Use request interceptors (`onConfig` for requests) to log the full request URL for debugging. Check your network tab for actual request URLs and server responses. Adjust `timeout` if network conditions require more time.","cause":"Incorrect `baseURL` or API endpoint configuration in `appConfig.request`, a problem with the backend service, or an excessively short timeout.","error":"Error: timeout of 5000ms exceeded"}],"ecosystem":"npm"}