当前位置: 首页 > 工具软件 > Base-env > 使用案例 >

Taro 小程序 NODE-ENV 环境变量

曾嘉荣
2023-12-01

cross-env:需要安装依赖,使用cnpm i cross-env -D

package.json:

{
  "name": "myApp",
  "version": "1.0.0",
  "private": true,
  "description": "我的taro项目1",
  "templateInfo": {
    "name": "default",
    "typescript": false,
    "css": "sass"
  },
  "scripts": {
    "build:weapp:dev": "cross-env NODE_ENV=dev taro build --type weapp",
    "build:weapp:test": "cross-env NODE_ENV=test taro build --type weapp",
    "build:weapp:prd": "cross-env NODE_ENV=prd taro build --type weapp",
    "build:swan": "taro build --type swan",
    "build:alipay": "taro build --type alipay",
    "build:tt": "taro build --type tt",
    "build:h5": "taro build --type h5",
    "build:rn": "taro build --type rn",
    "build:qq": "taro build --type qq",
    "build:jd": "taro build --type jd",
    "build:quickapp": "taro build --type quickapp",
    "dev:weapp": "cross-env NODE_ENV=dev npm run build:weapp:dev -- --watch",//原本是"dev:weapp": "npm run build:weapp -- --watch"
    "test:weapp": "cross-env NODE_ENV=test npm run build:weapp:test -- --watch",
    "pro:weapp": "cross-env NODE_ENV=pro npm run build:weapp:prd -- --watch",/npm run build:weapp:prd:prd不能改,否则会报错
    "dev:swan": "npm run build:swan -- --watch",
    "dev:alipay": "npm run build:alipay -- --watch",
    "dev:tt": "npm run build:tt -- --watch",
    "dev:h5": "npm run build:h5 -- --watch",
    "dev:rn": "npm run build:rn -- --watch",
    "dev:qq": "npm run build:qq -- --watch",
    "dev:jd": "npm run build:jd -- --watch",
    "dev:quickapp": "npm run build:quickapp -- --watch"
  },
  "browserslist": [
    "last 3 versions",
    "Android >= 4.1",
    "ios >= 8"
  ],
  "author": "",
  "dependencies": {
    "@babel/runtime": "^7.7.7",
    "@tarojs/components": "3.3.5",
    "@tarojs/runtime": "3.3.5",
    "@tarojs/taro": "3.3.5",
    "@tarojs/react": "3.3.5",
    "react-dom": "^17.0.0",
    "react": "^17.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.8.0",
    "@tarojs/mini-runner": "3.3.5",
    "@tarojs/webpack-runner": "3.3.5",
    "@types/react": "^17.0.2",
    "@types/webpack-env": "^1.13.6",
    "babel-preset-taro": "3.3.5",
    "cross-env": "^7.0.3",
    "eslint": "^6.8.0",
    "eslint-config-taro": "3.3.5",
    "eslint-plugin-import": "^2.12.0",
    "eslint-plugin-react": "^7.8.2",
    "eslint-plugin-react-hooks": "^4.2.0",
    "stylelint": "9.3.0"
  }
}

该配置文件,使用npm run dev:weapp可以运行成功,process.env.NODE_ENV='development';使用npm run test:weapp,process.env.NODE_ENV='test';使用npm run pro:weapp,process.env.NODE_ENV='production';

config/dev.js:

module.exports = {
  env: {
    NODE_ENV: '"development"'
  },
  defineConstants: {
  },
  mini: {},
  h5: {}
}

config/prod.js:

module.exports = {
  env: {
    NODE_ENV: '"production"'
  },
  defineConstants: {
  },
  mini: {},
  h5: {
    /**
     * 如果h5端编译后体积过大,可以使用webpack-bundle-analyzer插件对打包体积进行分析。
     * 参考代码如下:
     * webpackChain (chain) {
     *   chain.plugin('analyzer')
     *     .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
     * }
     */
  }
}

config/test.js:

module.exports = {
    env: {
      NODE_ENV: '"test"'
    },
    defineConstants: {
    },
    mini: {},
    h5: {}
  }
  

config/index.js:

const config = {
  projectName: 'myApp',
  date: '2021-8-31',
  designWidth: 750,
  deviceRatio: {
    640: 2.34 / 2,
    750: 1,
    828: 1.81 / 2
  },
  sourceRoot: 'src',
  outputRoot: 'dist',
  plugins: [],
  defineConstants: {
  },
  copy: {
    patterns: [
    ],
    options: {
    }
  },
  framework: 'react',
  mini: {
    postcss: {
      pxtransform: {
        enable: true,
        config: {

        }
      },
      url: {
        enable: true,
        config: {
          limit: 1024 // 设定转换尺寸上限
        }
      },
      cssModules: {
        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    }
  },
  h5: {
    publicPath: '/',
    staticDirectory: 'static',
    postcss: {
      autoprefixer: {
        enable: true,
        config: {
        }
      },
      cssModules: {
        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    }
  }
}

module.exports = function (merge) {
  console.log(process)
  const buildConfig = {
    env: {
      BUILD_ENV: JSON.stringify(process.env.NODE_ENV)
    }
  }
  if (process.env.NODE_ENV === 'dev') {
    return merge({}, config, require('./dev'),buildConfig)
  }
  if(process.env.NODE_ENV==='test'){
    return merge({},config,require('./test'),buildConfig)
  }
  return merge({}, config, require('./prod'),buildConfig)
}

自己新建了一个文件夹utils存放封装的请求代码、接口地址等:

utils/env.js

let config = {
    development: {
     baseUrl:'xxx',
    },
    test: {
      baseUrl: 'xxx', 
    },
    production: {
      baseUrl: 'xxx',
    },
  };
  console.log(process.env.NODE_ENV)
  let env = config[process.env.NODE_ENV];
  
  export default env;
  

utils/request.js

import env from "./env"
import Taro from '@tarojs/taro'
/**
 * 声明请求对象
 */
let requestHandler = {
    params: {},
    closeLoading: false, //默认显示Toast,如果设置true则不会显示Toast
    success: function (res) {
      // success
    },
    fail: function () {
      // fail
    },
  }
  /**
   * GET请求
   * @param {*} requestHandler 
   */
  export async function GET(requestHandler) {
    httpRequest('GET', requestHandler)
  }
  /**
   * POST请求
   * @param {*} requestHandler 
   */
  export async function POST(requestHandler) {
    httpRequest('POST', requestHandler)
  }
  /**
   * http request 请求
   * @param {http method} method 
   * @param {*} requestHandler 
   */
  export async function httpRequest(method, requestHandler) {
    //注意:可以对params签名等处理
    let params = requestHandler.params
    // params = apiParamSign(params)
    let closeLoading = requestHandler.closeLoading
  
    if (!closeLoading) {
      Taro.showLoading({
        title: '加载中',
        mask: true,
      })
    }
    console.log(env)
    Taro.request({
      url: env.baseUrl,
      data: params,
      method: method,// OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // responseType: 'text',
      // credentials: 'include',
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
      },
      mode: 'no-cors',
      success: function (res) {
        console.log('request success!')
        console.log(res.data)
        if (!closeLoading) {
          Taro.hideLoading()
        }
        if (res.data.status == 'success') {
          requestHandler.success(res.data)
        } else if (res.data.status == 'error') {
          //错误回调处理
          requestHandler.fail()
          Taro.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        } else {
          //请他情况当成失败处理
          requestHandler.fail()
        }
  
  
      },
      fail: function (res) {
        console.log('request failed!')
        if (!closeLoading) {
          Taro.hideLoading()
        }
        //错误回调处理
        requestHandler.fail()
      }
    })
  
  }
  
  /**
   * 系统参数和功能参数做签名(按照服务端接口标准制定)
   * @param {传入功能参数} params 
   */
  function apiParamSign(params) {
    let sysParams = {}
    let date = new Date();
    let month = date.getMonth() + 1
    sysParams.date = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();;
    // data.task = date.getTime();
  
    sysParams.version = '1.0'
    sysParams.format = 'json'
    sysParams.flag = 'dev_flag'
  
    let data = {}
    //合并对象
    Object.assign(data, sysParams, params)
  
    let keys = []
    for (var k in data) {
      if (data.hasOwnProperty(k)) {
        keys.push(k);
      }
    }
    keys.sort();
    let paramsStr = "";
    for (var i = -0; i < keys.length; i++) {
      paramsStr += keys[i];
      paramsStr += data[keys[i]];
    }
    let tmp = md5(paramsStr).toUpperCase() + API_BASE_TOKEN;
    tmp = md5(tmp).toUpperCase();
    data.sign = tmp;
    return data;
  }
 

页面使用用例:

 componentDidMount() {
    const params = {}
    params.method = 'GET'
    params.user_name = 'USERNAME'
    params.password = 'PASSWOED'
    POST({
      params: params,
      closeLoading: true,
      success: function (res) {
        console.log(res)
      },
      fail: function (error) {
        console.log(error)
      }
    })
   }

创建项目时自动生成的package.json:

{
  "name": "myApp",
  "version": "1.0.0",
  "private": true,
  "description": "我的taro项目1",
  "templateInfo": {
    "name": "default",
    "typescript": false,
    "css": "sass"
  },
  "scripts": {
    "build:weapp": "taro build --type weapp",
    "build:swan": "taro build --type swan",
    "build:alipay": "taro build --type alipay",
    "build:tt": "taro build --type tt",
    "build:h5": "taro build --type h5",
    "build:rn": "taro build --type rn",
    "build:qq": "taro build --type qq",
    "build:jd": "taro build --type jd",
    "build:quickapp": "taro build --type quickapp",
    "dev:weapp": "npm run build:weapp -- --watch",
    "dev:swan": "npm run build:swan -- --watch",
    "dev:alipay": "npm run build:alipay -- --watch",
    "dev:tt": "npm run build:tt -- --watch",
    "dev:h5": "npm run build:h5 -- --watch",
    "dev:rn": "npm run build:rn -- --watch",
    "dev:qq": "npm run build:qq -- --watch",
    "dev:jd": "npm run build:jd -- --watch",
    "dev:quickapp": "npm run build:quickapp -- --watch"
  },
  "browserslist": [
    "last 3 versions",
    "Android >= 4.1",
    "ios >= 8"
  ],
  "author": "",
  "dependencies": {
    "@babel/runtime": "^7.7.7",
    "@tarojs/components": "3.3.5",
    "@tarojs/runtime": "3.3.5",
    "@tarojs/taro": "3.3.5",
    "@tarojs/react": "3.3.5",
    "react-dom": "^17.0.0",
    "react": "^17.0.0"
  },
  "devDependencies": {
    "@types/webpack-env": "^1.13.6",
    "@types/react": "^17.0.2",
    "@tarojs/mini-runner": "3.3.5",
    "@babel/core": "^7.8.0",
    "@tarojs/webpack-runner": "3.3.5",
    "babel-preset-taro": "3.3.5",
    "eslint-config-taro": "3.3.5",
    "eslint": "^6.8.0",
    "eslint-plugin-react": "^7.8.2",
    "eslint-plugin-import": "^2.12.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "stylelint": "9.3.0"
  }
}

build的还没有试过不同的script连不同的环境变量;封装的请求代码还需完善,这也都是网上找的。本文只是一边学习自己搭建小程序的环境,一边做的笔记。

 类似资料: