js dynamic import default JSON file All In One
<script setup lang="ts">
import { ref } from 'vue';
// import { useAppStore } from "../store/index";
import { useAppStore } from "@/store/index";
// 實例化 store
const store = useAppStore();
const log = console.log;
log(`store =`, store);
// Vue & js Types
// const props = defineProps({
// id: Number,
// name: String,
// });
// TypeScript & generic Types ✅
defineProps<{
id: number,
name: string,
}>();
const remoteUrl = `https://cdn.xgqfrms.xyz/json/cat.json`;
const localUrl = `@/json/cat.json`;
// const remoteUrl = `https://cdn.xgqfrms.xyz/json/cat.json`;
// const localUrl = `@/json/cat.json`;
// dynamic import JSON default ❌ 不支持 var 開頭 path
// const remoteJson = import(remoteUrl).default;
// const localJson = import(localUrl).default;
// console.log('remoteJson =', remoteJson);
// console.log('localJson =', localJson);
// dynamic import JSON default ✅
const fetchJSON = async () => {
// local promise default ✅
const localJson = (await import('@/json/cat.json')).default;
console.log('localJson =', localJson);
// ❌
const remoteJson = await import('https://cdn.xgqfrms.xyz/json/cat.json').then(res => {
console.log('res =', res);
return res.json();
});
console.log('remoteJson =', remoteJson);
};
fetchJSON();
let jsonString = ref('');
const url = `https://cdn.xgqfrms.xyz/json/cat.json`;
// async await
store.fetchData(url).then(json => {
jsonString.value = JSON.stringify(json, null, 4);
console.log('jsonString.value =', jsonString.value);
});
const updateMsg = () => {
store.$patch({
msg: "Hello Pinia 🍍!",
});
// store.updateMsg('Pinia 🍍');
}
</script>
bug
The above
dynamic import
cannot be analyzed byvite
.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
for supported dynamic import formats.
If this is intended to be left as-is, you can use the /* @vite-ignore */
comment inside the import() call to suppress this warning.
Plugin: vite:import-analysis
https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
solution ?
$ npm i -D @rollup/plugin-dynamic-import-vars
// rollup.config.js
import dynamicImportVars from '@rollup/plugin-dynamic-import-vars';
export default {
plugins: [
dynamicImportVars({
// options
})
]
};
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json".
Strict MIME type checking is enforced for module scripts per HTML spec.
demo
https://vueschool.io/lessons/synchronous-and-asynchronous-actions-in-pinia
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 發布文章使用:只允許注冊用戶才可以訪問!
原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!