import { chalk } from '@tarojs/helper' ; import { isArray , isString } from '@tarojs/shared' ; import type { IPluginContext , TaroPlatformBase } from '@tarojs/service' ; const spawn = require ( 'cross-spawn' ) ; const detectPort = require ( 'detect-port' ) ; interface IOptions { enabled ? : boolean ; port ? : string ; } export default function ( ctx , options ) { if ( process . env . NODE_ENV === 'production' || options . enabled === false ) return ; const port = Number ( options . port || '8097' ) ; detectPort ( port , ( err , availablePort ) => { if ( err ) { console . log ( `detectport 错误：${ err }` ) ; } if ( availablePort === port ) { console . log ( chalk . yellow ( '\n提示  ' ) + '正在启动 react-devtools...\n' ) ; spawn ( require . resolve ( 'react-devtools/bin' ) , { env : { ... process . env , PORT : port } } ) ; } } ) ; ctx . registerMethod ( { name : 'onSetupClose' , fn ( platform ) { injectRuntimePath ( platform ) ; } } ) ; ctx . modifyWebpackChain ( ( { chain } ) => { chain . plugin ( 'definePlugin' ) . tap ( args => { const config = args [ 0 ] ; config . __REACT_DEVTOOLS_PORT__ = port ; return args ; } ) ; chain . merge ( { module : { rule : { 'plugin-react-devtools' : { test : /react-reconciler\.(production|development)/ , loader : require . resolve ( './loader' ) } } } } ) ; } ) ; } function injectRuntimePath ( platform ) { const injectedPath = '@tarojs/plugin-react-devtools/dist/runtime' ; if ( isArray ( platform . runtimePath ) ) { platform . runtimePath . push ( injectedPath ) ; } else if ( isString ( platform . runtimePath ) ) { platform . runtimePath = [ platform . runtimePath , injectedPath ] ; } }