DEV Community

Peiwen Li
Peiwen Li

Posted on

An Intro to UmiJS

Why Umi?

Frontend development has been distinguished from backend for quite a while now. Many frameworks and plugins have been developed for frontend developemnt. Sometimes it's difficult to initialise a project because there are too many tools to choose from. To achieve this, UmiJS came to live.

Before everything else -

In order to use Umi (a frontend framework), you need to have NodeJS installed.

If you happened to be in China, you can install cnpm or tyarn for faster and safer package management:

$ npm install -g cnpm --registry=https://registry.npm.taobao.org
# OR
$ npm i yarn tyarn -g
Enter fullscreen mode Exit fullscreen mode

Then, you can use cnpm/tyarn to install your dependencies.

Umi Initialisation: Global

You can install umi globally:

$ tyarn global add umi
# OR
$ cnpm install umi -g
Enter fullscreen mode Exit fullscreen mode

Then, you can use 'umi generator' to fast start some pages:

  $ umi g page index
Enter fullscreen mode Exit fullscreen mode

This will first generate a pages folder under current directory inside which a index.js file and a index,css file will be created automatically. Each js file in pages directory will be interpreted as a route. Normally, this command is run at the root directory of the project.

  • umi dev
  $ umi dev
Enter fullscreen mode Exit fullscreen mode

This will start serving the pages on port 8000+.

Umi Initialisation: Scaffold

You can also initialise umi project with umi scaffold in a project folder

1. make a new directory

$ mkdir antd-testing
$ cd antd-testing
Enter fullscreen mode Exit fullscreen mode

2. install umi

$ tyarn create @umijs/umi-app
Enter fullscreen mode Exit fullscreen mode

Now the initialisation process has been complete, following up the configuration of the project.

3. Install Dependencies & Start

$ tyarn
Enter fullscreen mode Exit fullscreen mode

Then:

$ tyarn start
Enter fullscreen mode Exit fullscreen mode

PS: you can use 'Ant Design' default layout by installing pro-layout by running:

$ tyarn add @ant-design/pro-layout
# or
$ cnpm i @ant-design/pro-layout --save
Enter fullscreen mode Exit fullscreen mode

Then, edit .umirc.ts file:

import { defineConfig } from 'umi'

export default defineConfig({
  nodeModulesTransform: {
    type: 'none',
  },
  layout: {}, // add this line
  routes: [{ path: '/', component: '@/pages/index' }],
})
Enter fullscreen mode Exit fullscreen mode

Run script

Now you can run the following commands to start the server.

$ umi dev
# OR
$ cnpm run dev
# OR
$ tyarn start
Enter fullscreen mode Exit fullscreen mode

Routing

Conventional Routing (File Routing) - 约定式路由

The folder structure, i.e. files under src/pages, represents the default routing.

  • Dynamic Routing: by convention, folder named [post] will become a variable in the routes like so /index/:post
  • Nested Routing: by convention, if _layout.tsx exists in a sub-folder of pages folder, _layout.tsx becomes the parent component of all the other components within the same folder
  • Overall layout: by convention, index.tsx file in src/layouts folder is the parent component of all the components in src/pages folder
  • 404 Routing: by convention, 404.tsx in pages folder is the component renders 404 page
  • Extra Routing Attribute: before exporting a component, add this line HomePage.title = 'Home Page', now you can access an extra routing attribute title

Configured Routing - 配置式路由

If you are not satisfied with this routing method, configure your config/config.js/.umirc.ts file to appoint the routes yourself (i.e. configured routing (配置式路由) as opposed to the default conventional routing (约定式路由)):

export default {
  routes: [
    {
      exact: true,
      path: '/',
      component: '@pages/FirstPage', // relative path from `src` folder
      routes: [
        { path: '/list', component: 'List' },
        { path: '/listing', redirect: '/list' }, // redirecting to other routes
        { path: '/admin', component: 'Admin' },
      ],
    },
  ],
}
Enter fullscreen mode Exit fullscreen mode

NOTES: @ represents ./src -- referring to the relative path; it is the same as .. as in ../Firstpage

history: to navigate

In Umi, there are two ways to direct user from one page to another: <Link to="/link_url">Somewhere</Link> component and history.push('/link_url'):

import { history } from 'umi'

// simply redirecting
history.push('/list')

// redirecting with variables
history.push('/list?a=b')
history.push({
  pathname: '/list',
  query: {
    a: 'b',
  },
})

// go back
history.goBack()
Enter fullscreen mode Exit fullscreen mode

Build

$ cnpm run build
Enter fullscreen mode Exit fullscreen mode

Run this code to build the dist folder. Do not forget to install serve globally.

$ cnpm install serve -g
Enter fullscreen mode Exit fullscreen mode

Then you can serve the dist folder directly on port 5000:

$ serve ./dist
Enter fullscreen mode Exit fullscreen mode

plugins

To check the list of plugins in an umi project:

$ umi plugin list

# showing the keys
$ umi plugin list --key
Enter fullscreen mode Exit fullscreen mode

Once you know the key of a plugin, you can config the plugin in your config file:

export default {
  mock: false,
  // OR
  mock: { exclude: ['./foo'] },
}
Enter fullscreen mode Exit fullscreen mode

Mock data

Mock data lives in /mock folder. A tipical mockup api.ts file looks like this:

export default {
  // 支持值为 Object 和 Array
  'GET /api/users': { users: [1, 2] },
  // GET 可忽略
  '/api/users/1': { id: 1 },
  // 支持自定义函数,API 参考 express@4
  'POST /api/users/create': (req, res) => {
    // 添加跨域请求头
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.end('ok')
  },
}
Enter fullscreen mode Exit fullscreen mode

Now, if you visit /api/users, { users: [1, 2] } will be returned. GET key word can be omitted.

Mock.js

You can use mock.js to auto-generate some mockup data, visit the website for more info.

Environment Variables

DynamicImport

Top comments (0)