在commonjs的项目中使用esm和ts开发的sdk
- 效果
- 实现步骤
效果
在一些demo中, 大部分代码是commonjs规范开发的,但是要用到的sdk是ts开发的并且仅支持esm,
又不想配置很复杂的工程项目,可以这么做。如果你有更好的建议,希望能得到你的指点。
源码:https://github.com/thinkasany/nestjs-course-code/tree/master/demo/cjsAndEsm
实现步骤
创建tsconfig.json文件
{"compilerOptions": {"target": "es6","module": "commonjs","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"moduleResolution": "node","outDir": "./dist" // 输出目录},"include": ["service/*.ts"],"exclude": ["node_modules"]}
"scripts": {"test": "echo \"Error: no test specified\" && exit 1","start": "npx tsc && nodemon main.js"},
const Client = require('../dist/address'); module.exports = function (app) {app.get('/health', (req, res) => {return res.json({ message: 'OK', data: `Time Is ${new Date().toString()}` });});app.get('/address', async (req, res) => {const text = req.query.text; // 从请求参数中获取需要处理的文本try {const data = await Client.main(text);console.log('data', data);res.status(200).json({ message: 'Successfully processed the request.', data });} catch (error) {// 处理错误res.status(500).json({ error: error.message });}});
};