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';

相关推荐
wx_lidysun1 天前
Nextjs学习笔记
前端·react·next
无羡仙1 天前
从零构建 Vue 弹窗组件
前端·vue.js
源心锁1 天前
👋 手搓 gzip 实现的文件分块压缩上传
前端·javascript
源心锁1 天前
丧心病狂!在浏览器全天候记录用户行为排障
前端·架构
GIS之路1 天前
GDAL 实现投影转换
前端
phltxy1 天前
从零入门JavaScript:基础语法全解析
开发语言·javascript
烛阴1 天前
从“无”到“有”:手动实现一个 3D 渲染循环全过程
前端·webgl·three.js
BD_Marathon1 天前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
Kagol1 天前
JavaScript 中的 sort 排序问题
前端·javascript
eason_fan1 天前
Service Worker 缓存请求:前端性能优化的进阶利器
前端·性能优化