前端新手如何用vite构建小程序中使用的模块(以AES加密模块crypto-js为例)

如果你只是想简单地把在vite项目中使用的模块引入到小程序中,不妨试试库模式。以crypto-js为例,你需要写两个JS文件:
一个是构建脚本,类似于vite.config.js;

// build.cjs
const {build}=require('vite'),
path=require('path');

build({
  publicDir:false,
  configFile:false,
  runtimeCompiler: true,
  build: {
    lib:{
      entry:path.resolve(__dirname,`crypto-js.js`), // 入口文件就是模块内容文件
      formats:['cjs'], // 格式一定要写cjs
      fileName:format=>'crypto-js.js' // 输出文件名,无关紧要,打包好后可以再改
    },
  }
})

一个是模块内容,vite会将它导出的default模块打包为小程序中的module.exports对象。

// crypto-js.js
import CryptoJS from 'crypto-js';
export default CryptoJS;

最后用node运行构建脚本即可:

node .\path\to\build.cjs

你可能感兴趣的:(前端,前端,小程序,javascript)