umi之define屬性

含義:

用于提供給項(xiàng)目全局中可用的常量,每個(gè)頁面都可使用

例:

在跟目錄.umirc文件里進(jìn)行配置 define

import { defineConfig } from 'umi';

export default defineConfig({
  nodeModulesTransform: {
    type: 'none',
  },
  routes: [
    { path: '/', component: '@/pages/index' }
  ],
  fastRefresh: {},

  // DefinePlugin全局常量
  define:{
    'stateDemo':'1000'
  }
});

頁面中的使用

import styles from './index.less';
import React, { Component } from 'react'

export default class index extends Component{

  // 在生命周期里進(jìn)行打印
  componentDidMount(){
    console.log(stateDemo)
  }

  render(){
    return (
      <div>
        <h1 className={styles.title}>Page index</h1>
      </div>
    );
  }
}

在控制臺(tái)查看


image.png

問題:tsx中報(bào)錯(cuò)提示找不到stateDemo名稱

在網(wǎng)上找到了2種解決方案,我這里第二種方式解決了

解決方法:

  1. 使用完整引用:process.env.stateDemo
  2. 全局聲明 FOO:在 typings.d.ts 文件中,添加 declare const stateDemo: string // string 是 FOO 的數(shù)據(jù)類型,如果類型不定,直接寫成 any 吧
    如:


    image.png

這樣就可以完美使用了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容