简体   繁体   English

错误:必须使用导入来加载 ES 模块 - 使用 Typescript 和 Node

[英]Error: Must use import to load ES Module - Using Typescript and Node

Background背景

Tried to improve my error coding visibility and structure and decided to add the dependency ''' chalk ''', which requires Pure ESM.试图提高我的错误编码可见性和结构,并决定添加依赖项 ''' chalk ''',这需要 Pure ESM。 Originally, my ts.config/package.json was a common.js file and did not declare the "type" as "module".最初,我的 ts.config/package.json 是一个 common.js 文件,没有将“类型”声明为“模块”。 Made some changes as following chalk documentation and similar stack overflow troubleshooting.按照 chalk 文档和类似的堆栈溢出故障排除进行了一些更改。 Upon reloading my app, I receive this error:重新加载我的应用程序后,我收到此错误:

Error错误

[user] 
[user] > user@1.0.0 start
[user] > ts-node-dev src/index.ts
[user]
[user] [INFO] 02:43:13 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.8.0, typescript ver. 4.7.2)
[user] Compilation error in /app/src/index.ts
[user] Error: Must use import to load ES Module: /app/src/index.ts
[user]     at Object.<anonymous> (/app/src/index.ts:1:7)
[user]     at Module._compile (node:internal/modules/cjs/loader:1105:14)
[user]     at Module._compile (/app/node_modules/source-map-support/source-map-support.js:568:25)
[user]     at Module.m._compile (/tmp/ts-node-dev-hook-07536074778072654.js:69:33)
[user]     at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
[user]     at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-07536074778072654.js:114:20)
[user]     at require.extensions.<computed> (/tmp/ts-node-dev-hook-07536074778072654.js:71:20)
[user]     at Object.nodeDevHook [as .ts] (/app/node_modules/ts-node-dev/lib/hook.js:63:13)
[user]     at Module.load (node:internal/modules/cjs/loader:981:32)
[user]     at Function.Module._load (node:internal/modules/cjs/loader:827:12)
[user] [ERROR] 02:43:13 Error: Must use import to load ES Module: /app/src/index.ts

The following the changes I made to require requirements that I believe were neccessary?:以下是我为要求我认为必要的要求所做的更改?:

package.json package.json

{
  "name": "user",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "ts-node-dev src/index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/cookie-parser": "^1.4.3",
    "@types/express": "^4.17.13",
    "@types/jsonwebtoken": "^8.5.8",
    "@types/morgan": "^1.9.3",
    "@types/multer": "^1.4.7",
    "axios": "^0.27.2",
    "bcrypt": "^5.0.1",
    "body-parser": "^1.20.0",
    "chalk": "^5.0.1",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "dependencies": "^0.0.1",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "joi": "^17.6.0",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^4.6.0",
    "mongoose": "^6.3.3",
    "morgan": "^1.10.0",
    "multer": "^1.4.4",
    "nodemailer": "^6.7.5",
    "typescript": "^4.7.2",
    "uuid": "^8.3.2",
    "validator": "^13.7.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.16",
    "ts-node-dev": "^2.0.0"
  }
}

index.ts索引.ts

import mongoose from "mongoose";
import  app  from "./app";

const dbURI ='blabla' */
let PORT = 3000; /* process.env.PORT */

async function start() {

//T:              Connecting to MongoDB Database
    try{
        await mongoose
            .connect(dbURI)
            console.log(`connected to DB!`);        
    }catch(err) {
        console.log(err);
    };
    app.listen(PORT,()=>{
    console.log(
        `connected to PORT: ${PORT} and listening...although it may not bee that port`)
    });
}

start()

ts.config配置文件

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "ESNext",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "ESNext",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
     "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single 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. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
   "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'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": [
    "src/**/*"
  ]
}

Edit:File I called chalk in to test编辑:我调用粉笔进行测试的文件

import express from "express";
import { NotFoundError } from "./errors/NotFoundError";
import errorHandler from "./middleware/error-handler";
import userIndex from "./routes/userIndex";
import morgan from "morgan"
import cookieParser from "cookie-parser";
import chalk from 'chalk'



const app = express();
app.use(express.json());
app.use(cookieParser());
app.set("trust proxy", true);

const log = console.log;


// I tried all methods below...
app.use(
    morgan(
    // "dev", 
    function (tokens, req, res) {
        return [
            chalk.red (tokens.method(req, res)),
            chalk.green(tokens.url(req, res)),
            chalk.yellow(tokens.status(req, res),"-"),
            chalk.bgBlueBright(tokens["response-time"](req, res), "ms"),
            chalk.cyan(tokens['date'](req, res),'web'),
            chalk.blue(tokens.res(req, res, "content-length")),
        ].join(" ");
    }) 
    ) 
    
log(chalk.red('I'm red'))
log(chalk.green(
    'I am a green line ' +
    chalk.blue.underline.bold('with a blue substring') +
    ' that becomes green again!'
));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));

    app.use(morgan( function (tokens, req, res) {
        return chalk.yellow(tokens['date'](req, res),'web')
        + ' ' + chalk.blue(tokens['remote-addr'](req, res))
        + ' ' + chalk.cyanBright(tokens.method(req, res))
        + ' ' + chalk.green(tokens.url(req, res))
        + ' ' + chalk.magentaBright(tokens.status(req, res))
        + ' ' + chalk.red(tokens['response-time'](req, res))
    }))


 app.use(morgan(`
:remote-addr :remote-user :method :url :status :res[content-length] - :response-time ms :date[web]
`)); 

app.use('/users', userIndex);

app.all("*", async (req, res, next) => {
    next(new NotFoundError());
});

app.use(errorHandler);

export default app ;

Seems that I have found a resolution after spending hours on that... I think it may help someone, as I've seen no such answer on Stackoverflow.似乎我在花了几个小时之后找到了解决方案......我认为它可能会对某人有所帮助,因为我在 Stackoverflow 上没有看到这样的答案。

The problem was in ts-node-dev .问题出在ts-node-dev No one would guess.没有人会猜到。 But there is an open bug on that in their repo.但是在他们的回购协议中有一个开放的错误 Of course it has nothing to do with chalk .当然跟chalk没有关系。 And of course as the first step one needs to fix the project to work with ESM as described in many places (a good explanation sits in chalk repo ).当然,作为第一步,需要修复项目以使用 ESM,如许多地方所述(一个很好的解释位于chalk repo中)。

To check it is ts-node-dev problem you may simply run tsc (original TS compiler) from your project root.要检查它是否是ts-node-dev问题,您可以简单地从项目根目录运行tsc (原始 TS 编译器)。 It didn't output this 'import' error for me, and after I fixed a few other errors it compiled everything successfully.它没有 output 对我来说这个“导入”错误,在我修复了一些其他错误后,它成功编译了所有内容。

Solution解决方案

So I uninstalled ts-node-dev and installed ts-node and nodemon instead, as recommended here .因此,我按照此处的建议卸载了ts-node-dev并安装了ts-nodenodemon

First of all you may check the ts-node compilation and run attempt succeeds via:首先,您可以通过以下方式检查ts-node编译并运行尝试成功:

node --loader ts-node/esm --inspect ./src/server.ts

Next, nodemon and ts-node should be run together to replace ts-node-dev :接下来, nodemonts-node应该一起运行以替换ts-node-dev

From command line: nodemon --exec node --loader ts-node/esm src/server.ts从命令行: nodemon --exec node --loader ts-node/esm src/server.ts

Or add it to scripts section in package.json (to use through npm run dev ):或者将其添加到package.json中的scripts部分(通过npm run dev使用):

"scripts": {
    ...
    "dev": "nodemon --exec node --loader ts-node/esm src/server.ts",
    ...
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 节点错误必须使用import来加载ES模块 - Node Error Must use import to load ES module Gulp 抛出错误“必须使用导入来加载 ES 模块” - Gulp throws error 'Must use import to load ES Module' ESLint - 错误:必须使用导入来加载 ES 模块 - ESLint - Error: Must use import to load ES Module ElectronJS:必须使用导入来加载 ES 模块 - ElectronJS: Must use import to load ES Module SSR with Node, Webpack, React, Express, Material UI, React Router - 错误 [ERR_REQUIRE_ESM]: 必须使用导入加载 ES 模块 - SSR with Node, Webpack, React, Express, Material UI, React Router - Error [ERR_REQUIRE_ESM]: Must use import to load ES Module 错误:必须使用 import 加载 ES 模块:不支持 ES 模块的 D:\\node_modules\\react-markdown\\index.js require() - Error: Must use import to load ES Module: D:\node_modules\react-markdown\index.js require() of ES modules is not supported webpack: “[ERR_REQUIRE_ESM]: Must use import to load ES Module” - 但我用的是 import! - webpack: “[ERR_REQUIRE_ESM]: Must use import to load ES Module” - But I AM using import! 更新 angular 时必须使用 import 加载 ES Module - Must use import to load ES Module while updating angular 必须使用import加载ES Module.eslintrc.js - Must use import to load ES Module .eslintrc.js 错误 [ERR_REQUIRE_ESM]: 必须使用 import 来加载 ES 模块 - Error [ERR_REQUIRE_ESM]: Must use import to load ES module
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM