Skip to content

Commit

Permalink
taro rn 支持 config/index.ts 文件 (#14201)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiqingchen authored Aug 6, 2023
1 parent 65f9423 commit 14bf92c
Show file tree
Hide file tree
Showing 27 changed files with 281 additions and 435 deletions.
3 changes: 0 additions & 3 deletions packages/babel-preset-taro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,8 @@
"@tarojs/helper": "workspace:*",
"@tarojs/shared": "workspace:*",
"babel-plugin-dynamic-import-node": "2.3.3",
"babel-plugin-global-define": "1.0.3",
"babel-plugin-jsx-attributes-array-to-object": "0.3.0",
"babel-plugin-minify-dead-code-elimination": "^0.5.2",
"babel-plugin-transform-imports-api": "1.0.0",
"babel-plugin-transform-react-jsx-to-rn-stylesheet": "workspace:*",
"core-js": "^3.6.5",
"lodash": "^4.17.21",
"metro-react-native-babel-preset": "^0.72.1",
Expand Down
122 changes: 0 additions & 122 deletions packages/babel-preset-taro/rn/index.js
Original file line number Diff line number Diff line change
@@ -1,114 +1,6 @@
const PLATFORM_TYPE = require('@tarojs/shared').PLATFORM_TYPE
const reactNativeBabelPreset = require('metro-react-native-babel-preset')
const { merge } = require('lodash')
const fs = require('fs')
/**
*
* 获取项目级配置
*
*/
let config
let rnConfig
function getProjectConfig () {
if (config) return config
const fileName = `${process.cwd()}/config/index.js`
if (fs.existsSync(fileName)) {
config = require(`${process.cwd()}/config/index`)(merge)
return config
} else {
console.warn('缺少项目基本配置')
config = {}
return config
}
}

function getRNConfig () {
const config = getProjectConfig()
if (rnConfig) return rnConfig
if (config.rn) {
rnConfig = config.rn
} else {
rnConfig = {}
}
return rnConfig
}

/**
* 配置环境变量
*/
function getEnv () {
const config = getProjectConfig()
const envConst = {
'process.env.TARO_ENV': 'rn',
'process.env.TARO_PLATFORM': PLATFORM_TYPE.RN,
}
if (config.env) {
Object.keys(config.env).forEach((key) => {
try {
envConst[`process.env.${key}`] = JSON.parse(config.env[key])
} catch (e) {
console.error('env环境配置有误' + config.env[key])
}
})
}
if (!config.env || !config.env.NODE_ENV) {
if (process.env.NODE_ENV === 'development') {
envConst['process.env.NODE_ENV'] = 'development'
} else {
envConst['process.env.NODE_ENV'] = 'production'
}
}
return envConst
}

function parseDefineConst (config) {
const result = {}
Object.keys(config.defineConstants).forEach((key) => {
try {
result[key] = JSON.parse(config.defineConstants[key])
} catch (e) {
console.error('defineConstants error: ', e)
result[key] = ''
}
})
return result
}

/**
* 配置常量
* @returns {*}
*/
function getDefineConstants () {
const config = getProjectConfig()
const rnconfig = getRNConfig()
const env = getEnv()
if (rnconfig.defineConstants) {
return {
...parseDefineConst(rnconfig),
...env
}
}
if (config.defineConstants) {
return {
...parseDefineConst(config),
...env
}
}
return env
}

function getCSSModule () {
const rnconfig = getRNConfig()
if (rnconfig.postcss && rnconfig.postcss.cssModules) {
return rnconfig.postcss.cssModules.enable
}
return false
}

module.exports = (_, options = {}) => {
if(!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development'
}
const {
decoratorsBeforeExport,
decoratorsLegacy
Expand All @@ -122,22 +14,10 @@ module.exports = (_, options = {}) => {
const nativeLibs = require('@tarojs/taro-rn/libList.js')
const nativeInterfaces = nativeApis.concat(nativeLibs)

const defineConstants = getDefineConstants()
const presets = []
const plugins = []
const { enableMultipleClassName = false, enableMergeStyle = false } = getRNConfig()

presets.push(reactNativeBabelPreset(_, options))
plugins.push(
// React 17 jsx runtime 兼容
[require('@babel/plugin-transform-react-jsx'), {
runtime: options.reactJsxRuntime || 'automatic'
}],
[require('babel-plugin-transform-react-jsx-to-rn-stylesheet'), { enableCSSModule: getCSSModule(), enableMultipleClassName }]
)
if (enableMergeStyle) {
plugins.push([require('babel-plugin-jsx-attributes-array-to-object'), { attributes: ['style'] }])
}
plugins.push(
[require('babel-plugin-transform-imports-api').default, {
packagesApis: new Map([
Expand All @@ -161,10 +41,8 @@ module.exports = (_, options = {}) => {
}
}
}],
[require('babel-plugin-global-define'), defineConstants]
)

// 添加一个默认 plugin, 与小程序/h5保持一致.
plugins.push(
[require('@babel/plugin-proposal-decorators'), {
decoratorsBeforeExport,
Expand Down
2 changes: 0 additions & 2 deletions packages/taro-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@
"@tarojs/plugin-doctor": "0.0.10",
"adm-zip": "^0.4.13",
"cli-highlight": "^2.1.11",
"dotenv": "^16.0.3",
"dotenv-expand": "^9.0.0",
"download-git-repo": "^2.0.0",
"envinfo": "^7.8.1",
"eslint": "^8.12.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/taro-cli/src/__tests__/dotenv-parse.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { dotenvParse } from '@tarojs/helper'
import { Kernel } from '@tarojs/service'
import * as path from 'path'

import CLI from '../cli'
import { dotenvParse } from '../util/index'

jest.mock('@tarojs/service')
const MockedKernel = Kernel as unknown as jest.Mock<Kernel>
Expand Down
4 changes: 2 additions & 2 deletions packages/taro-cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { fs } from '@tarojs/helper'
import { dotenvParse, fs, patchEnv } from '@tarojs/helper'
import { Config, Kernel } from '@tarojs/service'
import * as minimist from 'minimist'
import * as path from 'path'

import customCommand from './commands/customCommand'
import { dotenvParse, getPkgVersion, patchEnv } from './util'
import { getPkgVersion } from './util'

const DISABLE_GLOBAL_CONFIG_COMMANDS = ['build', 'global-config', 'doctor', 'update', 'config']

Expand Down
59 changes: 0 additions & 59 deletions packages/taro-cli/src/util/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { chalk, fs, isWindows } from '@tarojs/helper'
import { exec } from 'child_process'
import { parse } from 'dotenv'
import { expand } from 'dotenv-expand'
import * as path from 'path'

import type { IProjectConfig } from '@tarojs/taro/types/compile'

export function getRootPath (): string {
return path.resolve(__dirname, '../../')
}
Expand Down Expand Up @@ -105,61 +101,6 @@ export function clearConsole () {
}
}

// 支持 --env-prefix=TARO_APP_,aa 类型参数
export const formatPrefix = (prefixs: string | string[] = ['TARO_APP_']): string[] => {
const prefixsArr: string[] = (Array.isArray(prefixs) ? prefixs : prefixs.split(',')).map(prefix => prefix.trim()).filter(prefix => !!prefix)
return prefixsArr
}
export const dotenvParse = (root: string, prefixs: string | string[] = ['TARO_APP_'], mode?: string): Record<string, string> => {
const prefixsArr: string[] = formatPrefix(prefixs)

const envFiles = new Set([
/** default file */ `.env`,
/** local file */ `.env.local`,
])

if(mode) {
envFiles.add(/** mode file */ `.env.${mode}`)
envFiles.add(/** mode local file */ `.env.${mode}.local`)
}

let parseTemp = {}
const load = envPath => {
// file doesn'et exist
if(!fs.existsSync(envPath)) return
const env = parse(fs.readFileSync(envPath))
parseTemp = {
...parseTemp,
...env
}
}

envFiles.forEach(envPath => {
load(path.resolve(root, envPath))
})

const parsed = {}
Object.entries(parseTemp).forEach(([key, value]) => {
if(prefixsArr.some(prefix => key.startsWith(prefix)) || ['TARO_APP_ID'].includes(key)) {
parsed[key] = value
}
})
expand({ parsed })
return parsed
}

// 扩展 env
export const patchEnv = (config: IProjectConfig, expandEnv: Record<string, string>) => {
const expandEnvStringify = {}
for (const key in expandEnv) {
expandEnvStringify[key] = JSON.stringify(expandEnv[key])
}
return {
...config.env,
...expandEnvStringify
}
}

export function execCommand (params: {
command: string
successCallback?: (data: string) => void
Expand Down
2 changes: 2 additions & 0 deletions packages/taro-helper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
"chokidar": "^3.3.1",
"cross-spawn": "^7.0.3",
"debug": "4.3.4",
"dotenv": "^16.0.3",
"dotenv-expand": "^9.0.0",
"esbuild": "^0.14.27",
"find-yarn-workspace-root": "2.0.0",
"fs-extra": "^8.0.1",
Expand Down
61 changes: 61 additions & 0 deletions packages/taro-helper/src/dotenv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { parse } from 'dotenv'
import { expand } from 'dotenv-expand'
import * as fs from 'fs-extra'
import * as path from 'path'

import type { IProjectConfig } from '@tarojs/taro/types/compile'

// 支持 --env-prefix=TARO_APP_,aa 类型参数
export const formatPrefix = (prefixs: string | string[] = ['TARO_APP_']): string[] => {
const prefixsArr: string[] = (Array.isArray(prefixs) ? prefixs : prefixs.split(',')).map(prefix => prefix.trim()).filter(prefix => !!prefix)
return prefixsArr
}
export const dotenvParse = (root: string, prefixs: string | string[] = ['TARO_APP_'], mode?: string): Record<string, string> => {
const prefixsArr: string[] = formatPrefix(prefixs)

const envFiles = new Set([
/** default file */ `.env`,
/** local file */ `.env.local`,
])

if(mode) {
envFiles.add(/** mode file */ `.env.${mode}`)
envFiles.add(/** mode local file */ `.env.${mode}.local`)
}

let parseTemp = {}
const load = envPath => {
// file doesn'et exist
if(!fs.existsSync(envPath)) return
const env = parse(fs.readFileSync(envPath))
parseTemp = {
...parseTemp,
...env
}
}

envFiles.forEach(envPath => {
load(path.resolve(root, envPath))
})

const parsed = {}
Object.entries(parseTemp).forEach(([key, value]) => {
if(prefixsArr.some(prefix => key.startsWith(prefix)) || ['TARO_APP_ID'].includes(key)) {
parsed[key] = value
}
})
expand({ parsed })
return parsed
}

// 扩展 env
export const patchEnv = (config: IProjectConfig, expandEnv: Record<string, string>) => {
const expandEnvStringify = {}
for (const key in expandEnv) {
expandEnvStringify[key] = JSON.stringify(expandEnv[key])
}
return {
...config.env,
...expandEnvStringify
}
}
3 changes: 2 additions & 1 deletion packages/taro-helper/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ export const createDebug = (id: string) => require('debug')(id)

export { default as createBabelRegister, injectDefineConfigHeader } from './babelRegister'
export * from './constants'
export * from './dotenv'
export * from './esbuild'
export * as npm from './npm'
export { default as createSwcRegister } from './swcRegister'
export * from './terminal'
export * from './utils'
export * from './utils'
Loading

0 comments on commit 14bf92c

Please sign in to comment.