代码之家  ›  专栏  ›  技术社区  ›  Sankar

在nextjs中导入typescript常量失败

  •  0
  • Sankar  · 技术社区  · 6 月前

    在我的.ts文件中,我有:

    export type LocationState = "ACTIVE_LOCATION" | "DEFUNCT_LOCATION";
    
    export const LocationStates = {
      ACTIVE: "ACTIVE_LOCATION" as LocationState,
      DEFUNCT: "DEFUNCT_LOCATION" as LocationState,
    } as const;
    
    export interface Location {
      title: string;
      postal_address: string;
    }
    

    在我的nextjs应用程序中,当我导入Location接口时,它工作得很好。但是当我安装LocationState或LocationState时,我收到一个错误,它 Cannot resolve my library .

    // works    
    import { Location } from "@psankar/test-next-js-lib-library";
        
    // does not work
    import { LocationStates } from "@psankar/test-next-js-lib-library";
    

    在本地复制此问题的整个代码源可以在 https://github.com/psankar/test-next-js-lib 该代码在visualstudio代码中没有显示错误,但只有当我们访问nextjs导入const的路由时才会失败

    1 回复  |  直到 6 月前
        1
  •  1
  •   Redskinsjo    6 月前

    在里面 library/common/libray.ts :

    • 使用枚举可以改进您的实现
    • 将状态属性添加到 Location 接口
    • 确保 不要 declare enum interface

    试试这个:

    export enum LocationState {
      ACTIVE = "ACTIVE_LOCATION",
      DEFUNCT = "DEFUNCT_LOCATION",
    }
    export interface Location {
      title: string;
      postal_address: string;
      state: LocationState;
    }
    

    如果你复制粘贴了之前的代码,那么 nextjs/src/app/page.tsx :

    • 相应地重命名变量
    • 呼叫 location 传递eslint的变量
    import { LocationState } from "@psankar/test-next-js-lib-library";
    
    const location: Location = {
        title: "Test",
        postal_address: "123 Main St",
        state: LocationState.ACTIVE,
      };
    
    console.log(location);
    

    然后 ,in library ,运行你的 build 再次命令。 之后 ,in nextjs ,运行你的 建造 再次命令。

    它会起作用的