小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
三分钟实现 Vite + Vue3多入口项目开发
创建项目
# npm 6.x
$ npm init vite@latest <project-name> --template vue
# npm 7+,需要加上额外的双短横线
$ npm init vite@latest <project-name> -- --template vue
准备多入口文件
创建 Index 入口
项目根目录创建 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<link rel="icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Vite App Index</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/index/index.main.js"></script>
</body>
</html>
src 目录下创建 index 目录
src/index 目录下创建 Index.vue
<script setup></script>
<template>
<div>Hello Index</div>
</template>
<style></style>
src/index 目录创建 index-main.js
import { createApp } from 'vue'
import App from './Index.vue'
createApp(App).mount('#app')
创建 About 入口
项目根目录创建 about.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<link rel="icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Vite App About</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/about/about-main.js"></script>
</body>
</html>
src 目录下创建 about 目录
src/about 目录下创建 About.vue
<script setup></script>
<template>
<div>About</div>
</template>
<style></style>
src/about 目录创建 about-main.js
import {createApp} from 'vue'
import App from './About.vue'
createApp(App).mount('#app')
开发 配置 package.json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
},
}
yarn dev
localhost: 3000 => index 入口页面开发预览
localhost: 3000/about.html => about入口页面开发预览
打包配置 vite.config.js
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
input: {
index: path.resolve(__dirname, 'index.html'),
about: path.resolve(__dirname, 'about.html'),
},
},
}
})
yarn build
打包
# $ yarn build
yarn run v1.22.10
warning package.json: No license field
$ vite build
vite v2.6.5 building for production...
✓ 13 modules transformed.
dist/about.html 0.48 KiB
dist/index.html 0.48 KiB
dist/assets/index.03be285d.js 0.22 KiB / gzip: 0.20 KiB
dist/assets/about.c64be678.js 0.22 KiB / gzip: 0.19 KiB
dist/assets/plugin-vue_export-helper.ad25fb64.js 0.77 KiB / gzip: 0.43 KiB
dist/assets/vendor.82a8318e.js 48.81 KiB / gzip: 19.62 KiB
✨ Done in 1.48s.
打包后的 dist 目录
.
├── about.html
├── assets
│ ├── about.c64be678.js
│ ├── index.03be285d.js
│ ├── plugin-vue_export-helper.ad25fb64.js
│ └── vendor.82a8318e.js
├── favicon.ico
└── index.html
访问 打包后的文件 yarn serve
多入口项目创建完成