节点14.7客户端javascript中导入失败

问题描述

我想将我的JavaScript拆分为多个包,但我还想使用express,现在它是一个ES模块。同时拥有ES和cjs模块时,我无法将客户端Java脚本分解为模块。这是我最近的尝试,是在我自己的代码变得太损坏之后,我断网了。最近的示例也不起作用。我的节点是14.7

//package.json
"name": "esmtest","version": "1.0.0","description": "","main": "index.js","scripts": {
    "start": "node runner.js"
  },"keywords": [],"author": "","license": "ISC","dependencies": {
    "esm": "^3.2.25","express": "^4.17.1"
  }
}

//hi.mjs
export function sayHi(name) {
    return "Hi," + name + "!"
}

//hi-web.mjs
import express from "express";
import { sayHi } from "hi.mjs";

const app = express();

app.get("/",(req,res) => res.json({ "message": sayHi("LogRocket") }));

app.listen(8080,() => console.log("Hello ESM with @std/esm !!"));

//runner.js
require = require("@std/esm")(module);
module.exports = require("./hi-web.mjs").default;
''''
my latest error message:
S C:\Users\bubblegum\Desktop\esm test> npm start

> [email protected] start C:\Users\bubblegum\Desktop\esm test
> node runner.js

(node:4072) 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)
C:\Users\bubblegum\Desktop\esm test\runner.js:1
import { sayHi } from './hi.mjs'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1172:16)
    at Module._compile (internal/modules/cjs/loader.js:1220:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1277:10)
    at Module.load (internal/modules/cjs/loader.js:1105:32)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47

I've tried just about every combination of .js and .mjs,import and export,and upgrading node.  with the esm package I finally imported express but not all the modules.  It is usually the first import that doesn't work.

解决方法

证明@ std / esm不再起作用。而是使用esm。所以 '''' require = require(“ esm”)(module); module.exports = require(“ ./ hi-web.mjs”)。default;

source: https://github.com/standard-things/esm