Vite构建中HTML组件内JS能否转译为ES2015?
解决方案
1. 调整Vite配置,覆盖组件文件的转译范围
Vite默认不会处理HTML内嵌脚本或不在入口依赖链中的外部JS文件,需要通过配置将这些文件纳入转译流程。以下是完整的vite.config.js配置:
import { defineConfig } from 'vite'; import { createHtmlPlugin } from 'vite-plugin-html'; import fs from 'fs'; import path from 'path'; import { transform } from '@babel/core'; // 递归遍历组件文件夹,收集所有HTML文件 function scanComponentHtml(dir, htmlFiles = []) { const entries = fs.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory()) { scanComponentHtml(fullPath, htmlFiles); } else if (entry.name.endsWith('.html')) { htmlFiles.push(fullPath); } } return htmlFiles; } const componentHtmls = scanComponentHtml(path.resolve(__dirname, 'src/components')); export default defineConfig({ build: { target: 'es2015', rollupOptions: { // 确保所有组件相关JS被纳入转译 input: { ...componentHtmls.reduce((acc, htmlPath) => { const jsPath = path.join(path.dirname(htmlPath), path.basename(htmlPath, '.html') + '.js'); if (fs.existsSync(jsPath)) { const entryName = path.relative(__dirname, jsPath).replace(/\\/g, '/').replace('.js', ''); acc[entryName] = jsPath; } return acc; }, {}) }, output: { dir: 'dist/components', entryFileNames: '[name].js' } } }, plugins: [ createHtmlPlugin({ minify: true, pages: componentHtmls.map(htmlPath => ({ filename: path.relative('src/components', htmlPath), template: htmlPath })), transformHtml: (code, { filename }) => { // 转译内嵌<script>标签 code = code.replace(/<script(?! src)([\s\S]*?)>([\s\S]*?)<\/script>/gi, (match, attr, content) => { const { code: transpiled } = transform(content, { presets: [['@babel/preset-env', { targets: 'es2015' }]] }); return `<script${attr}>${transpiled}</script>`; }); // 转译并注入同目录外部JS code = code.replace(/<script src="([^"]+\.js)"><\/script>/gi, (match, src) => { const jsFullPath = path.join(path.dirname(filename), src); if (!fs.existsSync(jsFullPath)) return match; const rawJs = fs.readFileSync(jsFullPath, 'utf8'); const { code: transpiled } = transform(rawJs, { presets: [['@babel/preset-env', { targets: 'es2015' }]] }); return `<script>${transpiled}</script>`; }); return code; } }) ], esbuild: { target: 'es2015' } });
2. 依赖安装
执行以下命令安装必要的转译和处理依赖:
npm install --save-dev @babel/core @babel/preset-env vite-plugin-html
3. 两种组件的处理逻辑说明
- 内嵌
相关产品推荐
相关产品推荐

