taro(webpack)和uniapp(vite)中分别实现添加entry
目标:由于该工具类入口也需要被编译器识别,所以需要额外打包
两种实现如下
taro(vite版本参考下面)
// config/index.ts
import { defineConfig, type UserConfigExport } from '@tarojs/cli'
import webpack from 'webpack'
import { execSync } from 'child_process'
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin'
import devConfig from './dev'
import prodConfig from './prod'
// const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')
// 假如你使用 ts 配置,则使用下方 import 的写法
import { UnifiedWebpackPluginV5 } from 'weapp-tailwindcss/webpack'
import path from 'path'
// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig<'webpack5'>(async (merge, { }) => {
const baseConfig: UserConfigExport<'webpack5'> = {
projectName: 'demo01',
date: '2025-2-21',
designWidth: 750,
deviceRatio: {
640: 2.34 / 2,
750: 1,
375: 2,
828: 1.81 / 2
},
sourceRoot: 'src',
outputRoot: 'dist',
plugins: [
// '@tarojs/plugin-http'
],
defineConstants: {
},
alias:{
"@": path.resolve(__dirname, "..", "src"),
"@/components": path.resolve(__dirname, "..", "src/components")
},
// copy: {
// patterns: [
// {
// from: 'src/live-card/game.ts',
// to: path.join('dist', 'live-card/game.js'),
// }
// ],
// options: {
// }
// },
framework: 'react',
compiler: 'webpack5',
cache: {
enable: false // Webpack 持久化缓存配置,建议开启。默认配置请参考:https://docs.taro.zone/docs/config-detail#cache
},
mini: {
postcss: {
pxtransform: {
enable: true,
config: {
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
},
webpackChain(chain) {
// 复制这块区域到你的配置代码中 region start
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5,
args: [{
appType: 'taro'
}]
}
}
})
// region end
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
// console.log('hhhhhhhhhhhhhhhhhhh',liveCardEntry);
// chain.entry('app')
// .add(path.resolve(__dirname, '..','src/app.tsx')) // 添加入口 (失败的)
// .end();
// const extraEntryPath = path.resolve(__dirname, '..', 'src/live-card/game.ts');
chain.plugin('inject-livecard-entry').use(class {
apply(compiler) {
new webpack.EntryPlugin(
compiler.context,
path.resolve(__dirname, '..', 'src/live-card/game.ts'),
{ name: 'live-card' }
).apply(compiler);
}
});
// 修改 output 配置
chain.output
.path(path.resolve(__dirname,'..', 'dist')) // 默认输出目录
.filename((chunkData) => {
// 根据入口名称生成不同的输出文件路径和文件名
if (chunkData.chunk.name === 'live-card') {
return '[name]/game.js'; // liveCard 输出到 live-card/liveCard.js
}
return '[name].js'; // 默认输出
});
}
},
h5: {
publicPath: '/',
staticDirectory: 'static',
output: {
filename: 'js/[name].[hash:8].js',
chunkFilename: 'js/[name].[chunkhash:8].js'
},
miniCssExtractPluginOption: {
ignoreOrder: true,
filename: 'css/[name].[hash].css',
chunkFilename: 'css/[name].[chunkhash].css'
},
postcss: {
autoprefixer: {
enable: true,
config: {}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
}
},
rn: {
appName: 'taroDemo',
postcss: {
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
}
}
}
}
process.env.BROWSERSLIST_ENV = process.env.NODE_ENV
if (process.env.NODE_ENV === 'development') {
// 本地开发构建配置(不混淆压缩)
return merge({}, baseConfig, devConfig)
}
// 生产构建配置(默认开启压缩混淆等)
return merge({}, baseConfig, prodConfig)
})
亦可配置在打包时
import type { UserConfigExport } from "@tarojs/cli"
import path from "path";
export default {
logger: {
quiet: false,
stats: true
},
mini: {
webpackChain (chain) {
console.log('这里会执行的');
}
},
h5: {}
} satisfies UserConfigExport<'webpack5'>
uniapp(webpack版本参考上面)
// vite.config.ts
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import fs from 'fs'
import path from 'path'
// 递归扫描指定目录下的所有 .js 文件
function scanJsFiles(dir: string, baseDir = dir): Record<string, string> {
const files: Record<string, string> = {}
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.resolve(dir, entry.name)
if (entry.isDirectory()) {
Object.assign(files, scanJsFiles(fullPath, baseDir)) // 递归子目录
} else if (
entry.isFile() &&
entry.name.endsWith('.ts') &&
fullPath.includes('live-card')
) {
const relativePath = path.relative(baseDir, fullPath).replace(/\\/g, '/') // 保留相对路径
const name = relativePath.replace(/\.ts$/, '') // 去掉文件后缀
files[name] = fullPath // 保存到 input 对象
}
}
return files
}
// Vite 配置
export default defineConfig({
build: {
// 开发阶段启用源码映射:https://uniapp.dcloud.net.cn/tutorial/migration-to-vue3.html#需主动开启-sourcemap
sourcemap: process.env.NODE_ENV === 'development',
rollupOptions: {
input: scanJsFiles(path.resolve(__dirname, 'src')), // 自动扫描所有 JS 文件
output: {
entryFileNames: '[name].js', // 按照相对路径命名
dir: path.resolve(__dirname, 'dist/dev/mp-toutiao'), // 输出路径
sourcemap: false, // 禁止生成 .js.map 文件
},
external: ['@utils/http'], // 将模块显式标记为外部依赖
},
emptyOutDir: true, // 不清空输出目录
},
publicDir: 'static', // 静态资源文件夹
plugins: [
uni(), // 使用 uni 插件
// @ts-ignore
modifyAppJsonPlugin(),
],
})