基于typescript 开发njs 模块的一个玩法
如果体验了njs 模块的能力会发现njs 是一个很不错的js 模块,但是问题也不少,js 类型以及函数支持,同时npm模块支持也是
一个很大的问题,个人比较推荐的集成模式是基于rollup 构建
参考玩法
集成说明
因为缺少js 特性支持,我们可以基于core-js 进行扩展,对于npm 的集成我们可以使用rollup解决,njs-typescript-starter 是一个不错的模版,剋有很好的集成使用
rollup 参考配置
// @ts-check
import addGitMsg from 'rollup-plugin-add-git-msg'
import babel from '@rollup/plugin-babel'
import commonjs from '@rollup/plugin-commonjs'
import resolve from '@rollup/plugin-node-resolve'
import pkg from './package.json'
// List of njs built-in modules.
const njsExternals = ['crypto', 'fs', 'querystring']
const isEnvProd = process.env.NODE_ENV === 'production'
/**
* Plugin to fix syntax of the default export to be compatible with njs.
* (https://github.com/rollup/rollup/pull/4182#issuecomment-1002241017)
*
* @return {import('rollup').OutputPlugin}
*/
const fixExportDefault = () => ({
name: 'fix-export-default',
renderChunk: (code) => ({
code: code.replace(/\bexport { (\S+) as default };/, 'export default $1;'),
map: null,
}),
})
/**
* @type {import('rollup').RollupOptions}
*/
const options = {
input: 'src/mytest.ts',
external: njsExternals,
plugins: [
// Transpile TypeScript sources to JS.
babel({
babelHelpers: 'bundled',
envName: 'njs',
extensions: ['.ts', '.mjs', '.js'],
}),
// Resolve node modules.
resolve({
extensions: ['.mjs', '.js', '.json', '.ts'],
}),
// Convert CommonJS modules to ES6 modules.
commonjs(),
// Fix syntax of the default export.
fixExportDefault(),
// Plugins to use in production mode only.
// Add git tag, commit SHA, build date and copyright at top of the file.
addGitMsg(),
] : [],
],
output: {
file: pkg.main,
format: 'es',
},
}
export default options
说明
以上集成方案并不能彻底解决js 兼容问题,而且通过测试发现问题还是不少的,实际上对于简单模式使用njs 还不错,如果是比较复杂的,目前还说还是推荐
基于openresty+TypeScriptToLua 是很不错的选择,可以很好的利用lua 方便的生态
参考资料
https://github.com/jirutka/babel-preset-njs
https://github.com/jirutka/njs-typescript-starter
https://github.com/jirutka/nginx-testing
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2020-05-28 VictoriaMetrics v1.36.0 的一些新功能
2019-05-28 Kapitan 通用terraform&& kubernetes 配置管理工具
2019-05-28 sqler 集成 terraform v0.12 生成资源部署文件
2018-05-28 nexus helm proxy 集成&&问题解决
2018-05-28 nexus yum 私服集成
2018-05-28 nexus bower 集成使用
2018-05-28 nexus docker 私有镜像处理