Browse Source

在开发环境下,使用变量USE_MSW控制是否使用MSW,不使用MSW的话会直接和后端交互

dengdx 2 months ago
parent
commit
3967ed3a51
4 changed files with 36 additions and 1 deletions
  1. 1 0
      .env.development
  2. 31 0
      config/dev.ts
  3. 3 1
      src/app.tsx
  4. 1 0
      types/global.d.ts

+ 1 - 0
.env.development

@@ -1,2 +1,3 @@
 # 配置文档参考 https://taro-docs.jd.com/docs/next/env-mode-config
 # 配置文档参考 https://taro-docs.jd.com/docs/next/env-mode-config
 # TARO_APP_ID="开发环境下的小程序 AppID"
 # TARO_APP_ID="开发环境下的小程序 AppID"
+USE_MSW=false

+ 31 - 0
config/dev.ts

@@ -1,5 +1,9 @@
 import type { UserConfigExport } from '@tarojs/cli';
 import type { UserConfigExport } from '@tarojs/cli';
 import path from 'path';
 import path from 'path';
+import dotenv from 'dotenv';
+
+// 加载 .env.development 文件中的环境变量
+dotenv.config({ path: path.resolve(__dirname, '../.env.development') });
 
 
 export default {
 export default {
   logger: {
   logger: {
@@ -26,6 +30,33 @@ export default {
     // Use webpackChain to customize Webpack
     // Use webpackChain to customize Webpack
     // eslint-disable-next-line
     // eslint-disable-next-line
     webpackChain(chain, webpack) {
     webpackChain(chain, webpack) {
+      // 读取环境变量,告诉webpack在打包时,使用环境变量中定义的值 替换掉代码中的process.env.USE_MSW
+      // 打印环境变量,检查是否正确读取
+      console.log('环境变量 process.env.USE_MSW:', process.env.USE_MSW);
+      console.log('环境变量 process.env.NODE_ENV:', process.env.NODE_ENV);
+
+      // 确保使用正确的值,直接从.env文件读取
+      const useMSW = JSON.stringify(
+        process.env.USE_MSW === 'true' ? 'true' : 'false'
+      );
+      console.log('使用的 useMSW 值:', useMSW);
+
+      // 检查 define 插件是否已存在,如果不存在则先创建它
+      const hasDefinePlugin = chain.plugins.has('define');
+      if (!hasDefinePlugin) {
+        chain.plugin('define').use(webpack.DefinePlugin, [{}]);
+      }
+
+      // 然后再修改插件配置
+      chain.plugin('define').tap((args) => {
+        // 确保args[0]存在
+        if (!args[0]) {
+          args[0] = {};
+        }
+        args[0]['process.env.USE_MSW'] = useMSW;
+        console.log('DefinePlugin配置:', args[0]);
+        return args;
+      });
       chain.devServer.merge({
       chain.devServer.merge({
         setupMiddlewares: (middlewares, devServer) => {
         setupMiddlewares: (middlewares, devServer) => {
           devServer.app.get('/mockServiceWorker.js', (req, res) => {
           devServer.app.get('/mockServiceWorker.js', (req, res) => {

+ 3 - 1
src/app.tsx

@@ -10,8 +10,10 @@ import messages_en from './assets/i18n/messages/en';
 import messages_zh from './assets/i18n/messages/zh';
 import messages_zh from './assets/i18n/messages/zh';
 
 
 const messages = locale === 'zh' ? messages_zh : messages_en;
 const messages = locale === 'zh' ? messages_zh : messages_en;
+console.log(`process.env.USE_MSW: ${process.env.USE_MSW}`);
+console.log(`process.env.NODE_ENV: ${process.env.NODE_ENV}`);
 
 
-if (process.env.NODE_ENV === 'development') {
+if (process.env.NODE_ENV === 'development' && process.env.USE_MSW === 'true') {
   import('../mocks/server')
   import('../mocks/server')
     .then(({ server }) => {
     .then(({ server }) => {
       server.start({
       server.start({

+ 1 - 0
types/global.d.ts

@@ -33,5 +33,6 @@ declare namespace NodeJS {
      * @see https://taro-docs.jd.com/docs/next/env-mode-config#特殊环境变量-taro_app_id
      * @see https://taro-docs.jd.com/docs/next/env-mode-config#特殊环境变量-taro_app_id
      */
      */
     TARO_APP_ID: string;
     TARO_APP_ID: string;
+    USE_MSW?: string;
   }
   }
 }
 }