如何在ViteJS中修改输入目录以编译指定Demo资源?
如何用ViteJS指定Demo页面的编译文件?
项目结构
my-plugin/ ├─ demo/ │ ├─ resources/js/ │ │ ├─ app.js <---- 需要作为编译入口(`npm run build:demo`) │ ├─ public/js/ │ │ ├─ app.js <---- Vite编译Demo后的输出目录 ├─ node_modules/ ├─ dist/ <---- 插件构建目录(正常工作 ✅,`npm run build:dist`) │ ├─ index.mjs │ ├─ index.umd.js ├─ src/ │ ├─ index.js ├─ index.html <---- GitHub Pages需要的Demo入口,不能修改位置 ├─ package.json
当前配置
package.json 脚本
// package.json ... "scripts": { "build:dist": "LIB_NAME=dist vite build", "build:demo": "LIB_NAME=demo vite build", "build": "npm run build:dist && npm run build:demo", }, ...
vite.config.js 配置
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'; const path = require('path'); const config = { dist: { build: { lib: { entry: path.resolve(__dirname, './src/index.js'), name: 'VueResponsiveVideoBackgroundPlayer', fileName: 'vue-responsive-video-background-player', }, rollupOptions: { external: ['vue'], output: { globals: { vue: 'Vue', }, exports: 'named', }, }, outDir: './dist', }, plugins: [ vue(), cssInjectedByJsPlugin(), ], }, demo: { // 需要修改的部分 // root: './demo/resources/js/', build: { outDir: './demo/public/js', }, plugins: [ vue(), cssInjectedByJsPlugin(), ], }, }; const currentConfig = config[process.env.LIB_NAME]; if (currentConfig === undefined) { throw new Error('LIB_NAME is not defined or is not valid'); } export default defineConfig({ ...currentConfig, plugins: [ vue(), cssInjectedByJsPlugin(), ], });
遇到的错误
[vite]: Rollup failed to resolve import "/demo/public/js/app.js" from "index.html".
This is most likely unintended because it can break your application at runtime...
解决方案
要实现以./demo/resources/js/app.js为入口,输出到./demo/public/js/app.js,需要调整vite.config.js的demo配置,并修正index.html的引用路径:
1. 修改vite.config.js中的demo配置
demo: { build: { outDir: './demo/public/js', rollupOptions: { // 指定Demo的入口文件 input: path.resolve(__dirname, './demo/resources/js/app.js'), output: { // 指定输出文件名,确保输出为app.js fileName: 'app.js' } } }, plugins: [ vue(), cssInjectedByJsPlugin(), ], },
2. 修正根目录index.html的引用路径
因为Vite构建Demo后,输出文件在demo/public/js/app.js,所以index.html中应该引用这个路径,而不是编译前的入口路径:
<!-- index.html --> <script type="module" src="/demo/public/js/app.js"></script>
3. 开发模式调试配置(可选)
如果需要在开发模式下调试Demo,可以给demo配置添加root和server选项,指定开发服务器的根目录和端口:
demo: { root: __dirname, // 根目录指向项目根,确保能访问到index.html server: { port: 5174, // 避免和插件构建的开发端口冲突 }, build: { outDir: './demo/public/js', rollupOptions: { input: path.resolve(__dirname, './demo/resources/js/app.js'), output: { fileName: 'app.js' } } }, plugins: [ vue(), cssInjectedByJsPlugin(), ], },
调整后运行npm run build:demo即可正确编译Demo入口文件,输出到指定目录,同时index.html也能正确引用编译后的文件。
内容的提问来源于stack exchange,提问作者Philipp Mochine
相关产品推荐
相关产品推荐

