文章原文链接(代码)
以云函数为例,来阐明。因为minapp-fetch
办法比拟多,当应用云函数开发时,引入一个办法,就会将整个包打到一起,导致index.js
文件十分臃肿。所以,在3.x
及当前的版本里,反对按需加载。其配置办法如下。
1.新增一个云函数
新增一个云函数test_cloud
,通过mincloud
命令,取到本地。
在根目录运行npm init
,初始化我的项目。
依据如下package.json
文件,执行npm install
或yarn
{ "name": "test_cloud", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack --mode production", "deploy": "mincloud deploy test_cloud ../" }, "author": "", "license": "ISC", "dependencies": { "lodash": "^4.17.20", "minapp-fetch": "^3.2.0" }, "devDependencies": { "@types/lodash": "^4.14.165", "ts-import-plugin": "^1.6.7", "ts-loader": "^8.0.12", "typescript": "^4.1.3", "webpack": "^5.10.3", "webpack-cli": "^4.2.0" }}
2.增加配置文件
在根目录新增webpack.config.js
,tsconfig.json
如下:
webpack.config.js文件
const tsImportPluginFactory = require('ts-import-plugin')module.exports = { entry: './src/index.ts', output: { path: __dirname, filename: 'index.js', }, resolve: { extensions: ['.ts', '.js', '.json'] }, module: { rules: [ { test: /\.(jsx|tsx|js|ts)$/, loader: 'ts-loader', options: { transpileOnly: true, getCustomTransformers: () => ({ before: [ tsImportPluginFactory({ libraryName: 'minapp-fetch', libraryDirectory: 'lib', camel2DashComponentName: false })] }), compilerOptions: { module: 'es2015' } }, exclude: /node_modules/, }, ] }, target: 'node',}
.tsconfig.json
{ "compilerOptions": { "outDir": "./", "noImplicitAny": false, "module": "ESNext", "target": "es2015", "allowJs": true }, "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"],}
3.开发应用
在根目录新建src/index.ts
,而后就能够欢快的写代码了。
通过import {} from 'xxx'
的形式引入,就能够主动实现按需加载啦。
因为云函数是main
接口,所以,导出要写成exports.main =
。
最终代码如下:
import {find, init} from 'minapp-fetch'import b from './b'const chunk = require('lodash/chunk') //lodash只能这样单个引入,不然会全副打包init('zx_cloud')exports.main = async function (event: any) { b() try{ let tempRes = await find('dev_infos', { p0: ['view_count', '=', 1], r: 'p0' }) return { content: tempRes.data.objects.toString(), content_type: "application/json", status_code: 200 } }catch(err){ console.log('err', err) } chunk(['a', 'b', 'c', 'd'], 2)}
4.文件目录
原文链接