xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js dynamic import default JSON file All In One

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 by vite.

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-21 18:55  xgqfrms  阅读(898)  评论(4编辑  收藏  举报