xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js import ESM module error All In One

Node.js import ESM module error All In One

SyntaxError: Cannot use import statement outside a module

$ node ./src/mkdir.js

# mjs
$ node --experimental-modules ./src/mkdir.mjs

# npm script
$ npm run mk


https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module

"type": "module"

{
  "type": "module",
  "scripts": {
    "mk": "node ./src/mkdir.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "xgqfrms",
  "license": "MIT",
  "devDependencies": {
    "ts-node": "^10.7.0"
  }
}

ReferenceError: __dirname is not defined

$ npm run mk

https://stackoverflow.com/questions/8817423/why-is-dirname-not-defined-in-node-repl

https://github.com/nodejs/help/issues/2907#issuecomment-671782092


__dirname = path.resolve(path.dirname(''));
__dirname = path.resolve();

__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD
import path from 'path';
const __dirname = path.resolve();

node .mjs & --experimental-modules flag

https://github.com/nodejs/node/issues/34995

https://www.cnblogs.com/xgqfrms/p/13591967.html

TypeScript to commonjs error

error TS1192: Module '"fs"' has no default export.

error TS1259: Module '"path"' can only be default-imported using the 'esModuleInterop' flag

import fs from "fs";
import path from "path";
import superagent from "superagent";
import * as CheerioAPI from "cheerio";

const log = console.log;

log('ESM ❌ __dirname = \n', __dirname);
log('commonjs ✅ __dirname = \n', __dirname);


var fs_1 = require("fs");
var path_1 = require("path");
var superagent_1 = require("superagent");
var CheerioAPI = require("cheerio");

var log = console.log;

log('ESM ❌ __dirname = \n', __dirname);
log('commonjs ✅ __dirname = \n', __dirname);

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-04 17:47  xgqfrms  阅读(111)  评论(4编辑  收藏  举报