简体   繁体   English

运行 Babel 转译代码时需要 JSON 文件引发 Node.js 加载程序错误“错误:找不到模块'example.json'”

[英]require a JSON file throws a Node.js loader error "Error: Cannot find module 'example.json'" when running Babel transpiled code

There are several similar questions related to importing or requiring JSON (.json) files when building the code in TypeScript.在 TypeScript 中构建代码时,有几个与导入或需要 JSON (.json) 文件相关的类似问题。 My question is specifically about requiring a JSON file in an ES6 module that is transpiled to the current node target using Babel (core and cli).我的问题特别是关于在使用 Babel(核心和 cli)转译到当前节点目标的 ES6 模块中需要 JSON 文件。 I see no config option like TypeScript's resolveJsonModule for Babel, which leads me to believe it should work without any config.我没有看到像 TypeScript 的resolveJsonModule for Babel 这样的配置选项,这让我相信它应该在没有任何配置的情况下工作。

I am importing a JSON file ( example.json ) from a JS file ( index.js ) in the same directory, by doing:我正在从同一目录中的 JS 文件( index.js )导入 JSON 文件( example.json ),方法是:

const myObj = {};
myObj.myJSON = require("./example.json");

I have also tried importing using the newer ES6 syntax as:我还尝试使用较新的 ES6 语法进行导入:

import * as myJson from "./example.json";

I am using VSCode, and in both cases the auto-complete suggests to me the correct relative path to the JSON file in the source code.我正在使用 VSCode,在这两种情况下,自动完成都会向我建议源代码中 JSON 文件的正确相对路径。

The directory looks like:该目录如下所示:

src/
  |_dir/
    |_index.js
    |_example.json

In both cases, when transpiling with the babel-cli using the command: babel src --out-dir build , the produced build looks like:在这两种情况下,当使用babel-cli使用以下命令进行编译时: babel src --out-dir build ,生成的构建看起来像:

src/
  |_dir/
    |_index.js

For some reason, the example.json file is not included, despite it being required in the compiled index.js file:出于某种原因, example.json文件不包括在内,尽管它在编译的index.js文件中是必需的:

...

const myObj = {};

myObj.myJSON = require("./example.json");
...

As such, when running the transpiled build with node using node build/index.js , it throws the error:因此,当使用node build/index.js运行带有节点的转译构建时,它会引发错误:

internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module './example.json'
Require stack:
- ...
- .../build/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (.../index.js:15:25)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    ...
  ]
}

Here is the relevant configuration:下面是相关配置:

package.json

  ...
  "scripts": {
    "build": "babel src --out-dir build",
    "start": "node build/index.js",
    ...
  },
  "devDependencies": {
    "@babel/cli": "^7.16.8",
    "@babel/core": "^7.16.7",
    "@babel/preset-env": "^7.16.8",
    ...
  },
  "dependencies": {
    "@babel/plugin-transform-runtime": "^7.16.8",
    ...
  }

.babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

I think the boring answer is that Babel only processes JavaScript files.我认为无聊的答案是 Babel 只处理 JavaScript 文件。 Anything that's not JavaScript (eg JSON) gets left behind, even though it "feels" like the JSON file is a code dependency that Babel should "just do the right thing with" (since you require d or import ed it) -- or at least give you an error or a warning.任何不是 JavaScript (例如 JSON)的东西都会被抛在后面,即使它“感觉”像 JSON 文件是 Babel 应该“做正确的事情”的代码依赖项(因为你require d 或import编辑它) - 或至少给你一个错误或警告。 But that is not how Babel was designed in this use-case.但这不是 Babel 在这个用例中的设计方式。

You need to do extra work to copy data files.您需要做额外的工作来复制数据文件。 I suggest three main alternatives to choose from:我建议三个主要的替代方案可供选择:

  1. Use a bundler like WebPack or Gulp which has tools for copying non-JS files around使用 WebPack 或 Gulp 之类的捆绑器,其中包含用于复制非 JS 文件的工具
  2. Use Babel's --copy-files which copies everything.使用 Babel 的--copy-files复制所有内容。 You can sprinkle in --ignore patterns to try to avoid copying things you don't want copied.您可以使用--ignore模式来避免复制您不想复制的内容。
  3. Use something like the shx npm package which lets you run Unix-style filesystem commands in a cross-platform way from inside package.json scripts. Use something like the shx npm package which lets you run Unix-style filesystem commands in a cross-platform way from inside package.json scripts.

"build": "babel src --out-dir build && npx shx cp src/*.json dist/"

use __dirname + '/example.json'使用 __dirname + '/example.json'

暂无
暂无

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

相关问题 node.js 在运行 babel 脚本时找不到模块 - node.js cannot find module when running babel script Gatsby - 错误:找不到模块 '..\node_modules\gatsby\dist\utils\babel-loader.js' - Gatsby - Error: Cannot find module '..\node_modules\gatsby\dist\utils\babel-loader.js' Babel成功地转译了ES6代码(node.js),但是当“ npm start”执行时,它会抛出“ SyntaxError:意外的令牌导入” - Babel transpiled ES6 code (node.js) successfully, but when do “npm start” it throws “SyntaxError: Unexpected token import ” 错误:找不到模块 './config.json' 需要堆栈:[...] {JS} - Error: Cannot find module './config.json' Require stack: [...] {JS} 需要一个 json 文件导致错误:找不到模块 - require a json file results in an error: Cannot find module 模块构建失败(来自 ./node_modules/babel-loader/lib/index.js):错误:找不到模块“./src/data” - Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Cannot find module './src/data' node.js:要求 json 文件返回未找到模块 - node.js: require json file returns MODULE NOT FOUND Node.js 要求本地文件抛出错误 - Node.js require local file throws an error 错误 in./src/app.js 模块构建失败(来自./node_modules/babel-loader/lib/index.js):错误:找不到模块'@babel/preset-present-env' - ERROR in ./src/app.js Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Cannot find module '@babel/preset-present-env' 当我尝试需要本地模块时,node.js 抛出错误 - node.js throws error when I try to require local module
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM