二、异步导入问题 代码示例
1、根据官方文档引入 pinia
// main.js
import * as Pinia from 'pinia';
export function createApp() {
const app = createSSRApp(App)
app.use(Pinia.createPinia());
return {
app,
Pinia
}
}
2、根据文档示例,新建store
// stores/counter.js
import {
defineStore
} from 'pinia';
import {
ref
} from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value = count.value + 1;
}
return {
count,
increment
};
});
3、在主页通过 微信小程序的 require.async 导入store。
会出现报错:
{errMsg: "module 'stores/counter.js' is not defined, require args is 'stores/counter.js'", mod: "stores/counter.js"}
同时开发者工具的资源管理器中,也没有出现 stores/counter.js 这个文件
// pages/index/index.vue
<script setup>
import {
onLoad
} from '@dcloudio/uni-app'
onLoad(async () => {
let file = await require.async(`../../stores/counter.js`)
console.log(111, file);
counter = file.useCounterStore()
console.log(222, counter);
})
</script>
4、作为对比,新建一个页面,在新页面静态导入这个store
// pages/test/test.vue
<script setup>
import {
useCounterStore
} from '@/stores/counter'
const counter = useCounterStore()
</script>
然后重新编译后,3 中的异步导入就能正常执行了
同时开发者工具的资源管理器中,也出现了 stores/counter.js 这个文件
所以,希望在只使用 require.async 的情况下,也能正常编译对应文件
普通的js文件,虽然能通过移动到static中,来确保不被忽略,但会打乱整体的文件结构。
而store文件,是不支持移动到static中的。
试试试试 (作者)
一、排查了应该是微信开发者工具【代码热重载】设置的冲突
二、示例代码和详细说明都写在单独的回复中了
2025-06-23 17:44