dev.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import type { UserConfigExport } from '@tarojs/cli';
  2. import path from 'path';
  3. import dotenv from 'dotenv';
  4. // 加载 .env.development 文件中的环境变量
  5. dotenv.config({ path: path.resolve(__dirname, '../.env.development') });
  6. export default {
  7. logger: {
  8. quiet: false,
  9. stats: true,
  10. },
  11. defineConstants: {
  12. MQTT_BROKER_URL_FROM_WEBPACK: '"ws://192.168.110.13:8083/mqtt"',
  13. },
  14. mini: {},
  15. h5: {
  16. sourceMapType: 'eval-source-map',
  17. publicPath: '/',
  18. devServer: {
  19. proxy: {
  20. '/dr': {
  21. target: 'http://192.168.110.13:6001', // 你的后端服务地址
  22. changeOrigin: true, // 允许跨域
  23. // pathRewrite: {
  24. // '^/dr/api': '' // 可选,用于重写路径
  25. // }
  26. },
  27. },
  28. host: '0.0.0.0', // 监听所有网络接口
  29. open: false, // 可选:是否自动打开浏览器
  30. port: 10086, // 可选:指定端口号
  31. static: {
  32. directory: path.resolve(__dirname, '../public'),
  33. },
  34. },
  35. // Use webpackChain to customize Webpack
  36. // eslint-disable-next-line
  37. webpackChain(chain, webpack) {
  38. // 读取环境变量,告诉webpack在打包时,使用环境变量中定义的值 替换掉代码中的process.env.USE_MSW
  39. // 打印环境变量,检查是否正确读取
  40. console.log('环境变量 process.env.USE_MSW:', process.env.USE_MSW);
  41. console.log('环境变量 process.env.NODE_ENV:', process.env.NODE_ENV);
  42. // 确保使用正确的值,直接从.env文件读取
  43. const useMSW = JSON.stringify(
  44. process.env.USE_MSW === 'true' ? 'true' : 'false'
  45. );
  46. console.log('使用的 useMSW 值:', useMSW);
  47. // 检查 define 插件是否已存在,如果不存在则先创建它
  48. const hasDefinePlugin = chain.plugins.has('define');
  49. if (!hasDefinePlugin) {
  50. chain.plugin('define').use(webpack.DefinePlugin, [{}]);
  51. }
  52. // 然后再修改插件配置
  53. chain.plugin('define').tap((args) => {
  54. // 确保args[0]存在
  55. if (!args[0]) {
  56. args[0] = {};
  57. }
  58. args[0]['process.env.USE_MSW'] = useMSW;
  59. console.log('DefinePlugin配置:', args[0]);
  60. return args;
  61. });
  62. chain.devServer.merge({
  63. setupMiddlewares: (middlewares, devServer) => {
  64. devServer.app.get('/mockServiceWorker.js', (req, res) => {
  65. res.set('Content-Type', 'application/javascript');
  66. res.sendFile(
  67. path.resolve(__dirname, '../public/mockServiceWorker.js')
  68. );
  69. });
  70. return middlewares;
  71. },
  72. });
  73. },
  74. },
  75. } satisfies UserConfigExport<'webpack5'>;