我有 3 个组件的基本 vue 应用程序和 Pinia 商店。我需要导出它并使用导出的 .js 文件来显示基本 html 文件中的组件。如果没有 Pinia 实现,它可以很好地工作,但我需要这家商店。在运行开发模式下与商店一起运行的应用程序也运行良好。所以问题出在 import Pinia 并调用probable:
const pinia = Pinia.createPinia();
app.use(pinia);
我用以下方法构建它:
npm run build
vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: './src/App.vue',
name: 'MyComponent',
fileName: (format) => `my-component.${format}.js`
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue'
}
}
}
}
});
vueApp 中的main.js
文件
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
错误
ReferenceError:Pinia 未定义
HTML 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Component in HTML</title>
<link rel="stylesheet" href="dist/style.css">
</head>
<body>
<div id="app">
<my-component></my-component>
</div>
<!-- Polyfill process.env for browser compatibility -->
<script>
window.process = {
env: { NODE_ENV: 'production' }
};
</script>
<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
<script src="https://unpkg.com/[email protected]/dist/pinia.iife.js"></script>
<script src="dist/my-component.umd.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
console.log(Vue);
console.log(Pinia);
console.log(window.Pinia);
const app = Vue.createApp({});
const pinia = Pinia.createPinia();
app.use(pinia);
app.component('my-component', MyComponent);
app.mount('#app');
});
</script>
</body>
</html>