dva使用yarn編譯出錯

story.Write(z)發表於2024-04-15

1. 報錯資訊

./src/models/example.jsModule build failed: TypeError: /Users/user/Desktop/learn-code/10.React/01_dva-came/src/models/example.js: path.isPrivate is not a function at Array.forEach ()
只要啟動專案,然後修改example程式碼,只要example發生改變就會報該錯誤,無論是新增註釋還是產生新的換行

2.原始程式碼

// example.js

import { routerRedux } from "dva/router";
// routerRedux == connected-react-redux
function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
}

export default {
  namespace: "counter",
  state: {
    count: 1,
  },
  //ddd

  subscriptions: {
    setup({ dispatch, history }) {
      // eslint-disable-line
    },
  },

  effects: {
    *asyncAdd(action, { put, call }) {
      yield call(delay, 1000);

      yield put({ type: "counter/add" });
    },
    *goto({ payload }, { put }) {
      yield put(routerRedux.push(payload));
    },
  },

  reducers: {
    add(state, action) {
      console.log("state", state);

      return {
        count: state.count + 1,
      };
    },
  },
};

// index.js

import dva, { connect } from "dva";
import { Router, Route } from "dva/router";

import React from "react";
import "./index.css";
console.log("Router", Route);

// 1. Initialize
const app = dva();

// 2. Plugins
// app.use({});

// 3. Model
app.model(require("./models/example").default);

// 4. Router
// app.router(require("./router").default);
let Counter = connect((state) => state.counter)((props) => {
  let { count, dispatch } = props;
  console.log("count", props);

  return (
    <div>
      <p>{count}</p>
      <button
        onClick={() =>
          dispatch({
            type: "counter/add",
          })
        }
      >
        +
      </button>
      <button onClick={() => dispatch({ type: "counter/asyncAdd" })}>
        async +
      </button>
      <button onClick={() => dispatch({ type: "counter/goto", payload: "/" })}>
        goto /
      </button>
    </div>
  );
});
const Home = (props) => <div>home</div>;
app.router(({ history }) => (
  <Router history={history}>
    {/* Router 下面只能有一個元素  */}
    <React.Fragment>
      <Route path="/" exact component={Home} />
      <Route path="/counter" component={Counter} />
    </React.Fragment>
  </Router>
));

// 5. Start
app.start("#root");

3.最終查詢原因

  • 並沒有找到具體是因為什麼,猜測原因是使用了yarn 重新安裝依賴導致
  • 如果重新使用npm 安裝依賴則恢復正常

++++++++++++++++++++++++++++++++++++++++++++++
經過測試發現,使用dva腳手架生成的專案如果後期使用了yarn安裝依賴,就會導致出現該錯誤

相關文章