错误[ERR_REQUIRE_ESM]:如何在节点12中使用es6模块?

时间:2019-07-23 17:58:12

标签: javascript node.js import es6-modules

来自https://2ality.com/2019/04/nodejs-esm-impl.html的节点12应该支持es6模块;但是,我一直收到错误消息:

问题:如何在节点12中使用es6模块做MVP?

package.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
{
  "name": "dynamic-es6-mod",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.mjs",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/index.mjs"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "globby": "^10.0.1"
  }
}

7 个答案:

答案 0 :(得分:3)

节点14 中,我通过变通办法解决了该问题。

解决方法的来源:https://github.com/eslint/eslint/issues/12319#issuecomment-535799024

简短摘要:

  1. 您的根级别package.json不支持ESM
  2. 子目录可以-在src目录中的package.json中放置{ "type": "module" }

PS:ESLint团队目前无法轻松解决它,仅由于核心设计...:(

答案 1 :(得分:1)

所有您需要做的就是添加标记-experimental-modules ,该标记支持新的es6 import / export语句,而且顺序很重要,如下所示。

    "start": "node --experimental-modules src/index.mjs "

答案 2 :(得分:1)

您必须在package.json文件中添加此行代码“ type”:“ module” ,如果我正确回答了问题,您将可以使用import语句而不是require < / p>

您的packege.json如下所示

{
  "name": "dynamic-es6-mod",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.mjs",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/index.mjs"
 },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
   "globby": "^10.0.1"
 }

}

答案 3 :(得分:0)

尝试使用npm的esm模块,该模块将支持es6(也可以在生产中使用)。

答案 4 :(得分:0)

对于 Node.js:

告诉 Node 忽略错误。

const Module = require('module')
const orig = Module._extensions['.js']
const fs = require('fs')
Module._extensions['.js'] = function (module, filename) {
  try {
    return orig(module, filename)
  } catch (e) {
    if (e.code === 'ERR_REQUIRE_ESM') {
      // From: https://github.com/nodejs/node/blob/c24b74a7abec0848484671771d250cfd961f128e/lib/internal/modules/cjs/loader.js#L1237-L1238
      const content = fs.readFileSync(filename, 'utf8')
      module._compile(content, filename)
      // --
      return
    }
    throw e
  }
}

使用 Babel 即时转译。

require('@babel/register', {
  ignore: (f) => {
    // Don't ignore the package we want to transpile.
    if (f.match('semver-regex') return false
    // Prevent babel transpiling anything else in `node_modules`.
    return f.match('node_modules')
  },
  overrides: [{
    // Set preset to be used to transpile our ESM package.
    test: /semver\-regex/,
    presets: ['es2015'],
  }]
})

// Call the rest of your code.
require('./index.js')

对于 Webpack:

做类似的事情,但使用 Babel 加载器并且没有 Node require 钩子。

答案 5 :(得分:-1)

经过反复尝试后,我通过完全迁移到 typescript 解决了这个问题。令人惊讶的是,它从根部运行:

package.json

{ 
   ...
   "type": "module",
   ...
}

babel.config.ts

export default api => {
  api.cache(true)
  return {
    presets: ['...'],
    plugins: ['...'],
    env: { '...': '...' },
  }
}

webpack.common.ts

import { common } from './webpack.common'
import webpack from 'webpack'
...

export default {
  entry: {
    '...': '...',
  },
  output: {
    '...': '...',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/i,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: [
                [
                  '@babel/preset-env',
                  {
                    '...': '...',
                  },
                ],
                '@babel/preset-react',
                '@babel/typescript',
              ],
              plugins: [
                ['babel-plugin-transform-require-ignore', {}],
                '@babel/plugin-proposal-class-properties',
                '@babel/plugin-proposal-object-rest-spread',
              ],
            },
          },
        ],
      },
      '...'
    ],
  },
}

tsconfig.json

{
  "compilerOptions": {
    "...": "..."
  },
  "include": ["..."],
  "exclude": ["..."],
  "linterOptions": {
    "exclude": ["..."]
  },
  "defaultSeverity": "..."
}

答案 6 :(得分:-2)

只需要更新节点:

运行:nvm install 15 nvm 使用 15

信用:https://www.youtube.com/watch?v=sUkCszM2gvU https://www.youtube.com/watch?v=sUkCszM2gvU