更新于 

Vue

Vue CLI

npm run build 报错

Syntax Error: Thread Loader(Worker 0)

Syntax Error: Thread Loader(Worker 0)
The “from” argument must be of type string. Received undefined.

npm run server 报错

Component provided template option but runtime compilation is not supported in this build of Vue.

Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias “vue” to “vue/dist/vue.esm-bundler.js”

问题描述

最近有个原本用 vue2+webpack 的项目,需要用 vue3+vite 进行重构,
原项目里用了很多使用字符串template构建的组件:

1
2
3
4
5
6
export const SearchResetGroupButtons = {
template: ` <div>组件</div> `,
props: ['prop1', 'prop2'],
data:()=>{return {}},
// ...
};

将这些代码重写到vite构建的新项目里时,报了上述的错误。

vite.runtimeCompiler实现template动态渲染

VueRouter

动态加载组件的vue项目打包后报错

问题描述

在写一个纯demo展示类的项目时(vite+vue3),
因为demo和demo之间彼此没什么关系,父子也毫无关系,
因此这些demo组件都能批量自动导入,

因为我懒得在页面上一个一个把组件写进去,所以就用如下代码根据路由参数自动导入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script setup>

import {getCurrentInstance, defineAsyncComponent} from "vue";
const {proxy} = getCurrentInstance()

const ThreeComp = defineAsyncComponent({
loader:()=>import(proxy.$route.query.router)
})

</script>

<template>
<!-- 动态组件 -->
<ThreeComp></ThreeComp>
</template>

这么写在本地运行时没出任何问题,
但是打包部署后发现程序运行时报组件引入的错误:

1
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
问题解决

这是因为在vite打包时没有检测到这些动态引入的组件,
因此这些组件实际上没有被打包进去,

所以这里我就放弃了动态引入组件的方式,
选择批量引入路由

在vite中批量引入可以通过import.meta.glob的方式:

router/index.js中添加批量引入的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function addRouter(){
const modules = import.meta.glob([
'@/components/GSAP/**.vue',
'@/components/three/CSS3D/**.vue',
])
for (const path in modules) {
modules[path]().then((mod) => {
const file = mod.default
router.addRoute({
path: "/" + file.__name,
name: file.__name,
component: file,
});
});
}
}

addRouter()