esm和cmj混用报错分析

elpis DSL领域模型开发时,引入pinia处理模版数据时报错

代码

menu.js

js 复制代码
const { defineStore } = require('pinia') ; 
import { ref } from 'vue';
export const useMenuStore = defineStore('menu',()=>{const menuList = ref([])})

business.js

js 复制代码
import {useMenuStore} from './menu.js' 
const menuStore = useMenuStore()
报错信息:

getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?

报错提示为useMenuStoreapp.use(pinia)之前运行了

问题分析:getActivePinia() 为检查当前是否存在活跃实例。webpack打包正常,node环境运行正常,浏览器访问报错。说明是运行时问题,boot.js中有app.use(pinia)实例化。最终定位menu.js 文件 cmj 和esm混用导致

问题解析:

cmj和esm加载时机

CommonJS: 同步加载,运行时确认依赖。

ESM: 异步加载,编译时编译确认依赖。

总结:

在webpack 编译时 定义好了useMenuStore ,但是没有 执行const { defineStore } = require('pinia') ; 。在运行时才执行const { defineStore } = require('pinia') ; 但是useMenuStore 早已经定义好,而此时business.js已经提前调用了useMenuStore(),导致Pinia实例未激活。

解决方案

const { defineStore } = require('pinia') ; 替换为import { defineStore } from 'pinia';

相关推荐
沐灵洛1 分钟前
构建 Mac App Store 应用须知(全)
前端
KaMeidebaby2 分钟前
卡梅德生物技术快报|蛋白修饰调控 NETosis 分子机制及实验研究进展
前端·数据库·人工智能·算法·百度
颜进强7 分钟前
Claude Code -16 文件引用与加载机制完整实践:从 CLAUDE.md 到 Skills 与 Subagents
前端·后端·ai编程
2501_940041747 分钟前
硬核全栈开发命题,覆盖高并发/实时/微服务
前端
风骏时光牛马15 分钟前
Bash变量未加双引号导致文件名含空格解析异常实战案例
前端
Vennn16 分钟前
Android自动化:使用 Web 方式实现某音未读消息检查与采集
前端·javascript·vue.js
Smilezyl18 分钟前
为了搞懂 AI Agent,我用 6000 行 JS 代码手搓了一个零依赖的 Coding Agent
前端·javascript·github
海鸥-w18 分钟前
前端学习python第三天笔记整理(list 列表,str字符串,tuple元组,set集合,dect,函数,类型注解)
前端·python·学习
flavor19 分钟前
Vue3 大屏适配组件(Scale / Rem 双方案一键切换)
前端
掰头战士20 分钟前
搞定JavaScript类型判断,一文就够了
javascript