我有一个像这样定义的node.js模块:
function sayHi(){
// do something
}
module.exports = sayHi;
并使用:
导入const sayHi = require('./sayHi.js');
当我切换到打字稿时,就这样创建了sayHi.ts
:
function sayHi():void {
// do something
}
export default sayHi;
这允许我使用以下命令从其他.ts
文件中导入
import sayHi from "./sayHi";
但是,旧的.js
文件需要立即更新为require('./sayHi.js').default
导出的属性。
有没有办法做到两全其美? ES6进口+ ES5需要吗?
tsconfig.json
---
{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"lib": [], /* Specify library files to be included in the compilation. */
"checkJs": false, /* Report errors in .js files. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": false, /* Generates corresponding '.map' file. */
"outDir": ".", /* Redirect output structure to the directory. */
"rootDir": ".", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"importHelpers": true, /* Import emit helpers from 'tslib'. */
"strict": true, /* Enable all strict type-checking options. */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
}
}
答案 0 :(得分:0)
我最终使用:
function sayHi(){...}
exports = sayHi
这与import sayHi from "./sayHi"
和const sayHi = require("./sayHi")
一起使用