当前位置: 首页 > 知识库问答 >
问题:

前端 - 请问,为何不能这样运行ts文件呢?

薛宜
2023-08-10

请问,为何不能这样运行ts文件呢?

文件util.ts

import ip from 'ip'export const getLocalIPs = () => {  //var ip = require("ip");  console.dir ( ip.address() );  return ip.address()}

文件:__test__/util.test.ts

export default {} import { getLocalIPs } from '../util'getLocalIPs()

然后我在执行:

npx ts-node __test__/util.test.ts 

的时候,报错:

npx ts-node  util.test.ts (node:61127) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.(Use `node --trace-warnings ...` to show where the warning was created)/Users/john/Desktop/projects/个人/nextjs/renderer/components/func/Traceroute/__test__/util.test.ts:1import { getLocalIPs } from '../util';^^^^^^SyntaxError: Cannot use import statement outside a module    at Object.compileFunction (node:vm:360:18)    at wrapSafe (node:internal/modules/cjs/loader:1084:15)    at Module._compile (node:internal/modules/cjs/loader:1119:27)    at Module.m._compile (/Users/john/.npm/_npx/1bf7c3c15bf47d04/node_modules/ts-node/src/index.ts:1618:23)    at Module._extensions..js (node:internal/modules/cjs/loader:1209:10)    at Object.require.extensions.<computed> [as .ts] (/Users/john/.npm/_npx/1bf7c3c15bf47d04/node_modules/ts-node/src/index.ts:1621:12)    at Module.load (node:internal/modules/cjs/loader:1033:32)    at Function.Module._load (node:internal/modules/cjs/loader:868:12)    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)    at phase4 (/Users/john/.npm/_npx/1bf7c3c15bf47d04/node_modules/ts-node/src/bin.ts:649:14)mba:__test__ john$ npx ts-node  util.test.ts (node:61376) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.(Use `node --trace-warnings ...` to show where the warning was created)/Users/john/Desktop/projects/个人/nextjs/renderer/components/func/Traceroute/__test__/util.test.ts:1export default {};^^^^^^SyntaxError: Unexpected token 'export'    at Object.compileFunction (node:vm:360:18)    at wrapSafe (node:internal/modules/cjs/loader:1084:15)    at Module._compile (node:internal/modules/cjs/loader:1119:27)    at Module.m._compile (/Users/john/.npm/_npx/1bf7c3c15bf47d04/node_modules/ts-node/src/index.ts:1618:23)    at Module._extensions..js (node:internal/modules/cjs/loader:1209:10)    at Object.require.extensions.<computed> [as .ts] (/Users/john/.npm/_npx/1bf7c3c15bf47d04/node_modules/ts-node/src/index.ts:1621:12)    at Module.load (node:internal/modules/cjs/loader:1033:32)    at Function.Module._load (node:internal/modules/cjs/loader:868:12)    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)    at phase4 (/Users/john/.npm/_npx/1bf7c3c15bf47d04/node_modules/ts-node/src/bin.ts:649:14)

请问,这个报错的原因是什么呢? 我已经在

文件:__test__/util.test.ts
添加了导出啊:

export default {} 

共有1个答案

东郭阳德
2023-08-10

package.json里设置"type": "module":

"type": "module"

或者tsconfig.json配置:

{  "compilerOptions": {    "module": "ESNext"  }}
 类似资料: