programing

ECMAScript 6에서 JSON 파일을 Import하려면 어떻게 해야 합니까?

stoneblock 2023. 2. 28. 23:11

ECMAScript 6에서 JSON 파일을 Import하려면 어떻게 해야 합니까?

ECMAScript 6의 JSON 파일에 액세스하려면 어떻게 해야 합니까?

다음 기능이 작동하지 않습니다.

import config from '../config.json'

JavaScript 파일을 Import하려고 하면 정상적으로 동작합니다.


https://www.stefanjudis.com/snippets/how-to-import-json-files-in-es-modules-node-js/

ES 모듈은 Node.js 랜드에서는 아직 상당히 새로운 모듈입니다(Node 14 이후 안정적입니다).모듈에는 모듈시스템이 내장되어 있어 톱레벨 등의 기능이 대기하고 있습니다.

Pawel Grzybek의 ES 모듈에 관한 유익한 글을 읽었는데, 오늘 ES 모듈에서는 JSON 파일을 Import할 수 없다는 것을 알게 되었습니다.

import info from `./package.json` assert { type: `json` };


const { default: info } = await import("./package.json", {
  assert: {
    type: "json",
  },
});

너무 아쉬워요. ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★require음음 such const data = require('./some-file.json')Node.js는 Node.js를 사용합니다.

그러나 현재 Node.js에서 Import Assertions를 사용할 수 있습니까?

기입 시 현재 Node.js LTS(v18.12)는 Import 어사션을 실험적인 것으로 마크하고 있습니다.

은 어떻게 해야 하는지에 설명하고 있습니다.JSONES 모듈에서는 아직 실험 기능을 사용하지 않을 수 있습니다.

옵션 1: JSON 파일을 직접 읽고 해석합니다.

Node에서는 Node.js를 .fs파일을 읽고 해석하는 작업을 직접 수행합니다.

import { readFile } from 'fs/promises';
const json = JSON.parse(
  await readFile(
    new URL('./some-file.json', import.meta.url)
  )
);

2: 활용( Common) 2: JSrequireSON の son son son son son

이 문서에는 JSON 파일을 로드하는 데 사용할 수 있는 것도 기재되어 있습니다.이 접근방식은 Pawel이 블로그 투고에서 조언하는 방식이다.

createRequire할 수 있습니다.JSrequire 모듈의 JS .JS " ( Node . js EcmaScript " JSON " " ) 。

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");

TypeScript 또는 Babel에서 json 파일을 코드로 Import할 수 있습니다.

// Babel

import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

참고 자료: https://hackernoon.com/import-json-into-typescript-8d465beded79

ES 모듈을 사용한 JSON Import는 2020년 중반에 TC39에 기능으로 제출되었으며, (이 편집 시점) 사양에 수용되기 전 마지막 단계인 3단계에 있습니다(자세한 내용은 https://github.com/tc39/proposal-json-modules 참조).착륙하면 다음과 같이 사용할 수 있습니다.

import someName from "./some/path/to/your/file.json";

서 ★★★★★someName는 JSON 데이터에 의해 설명되는 JS 객체의 변수 이름입니다(물론 JSON 소스에서 JavaScript를 Import하는 것은 "Import JSON"이 아닙니다).

예: " " " " " " " )를 사용하고 있는 :esbuild를 충분히 (예: 트랜스포일러babel그럼, 서포트에 대해 걱정할 필요 없이, 이 구문을 사용할 수 있습니다.

또는 JSON 파일을 소유할 수 있는 여유 있는 경우 최소 추가 코드를 사용하여 JSON을 유효한 JS 파일로 변환할 수도 있습니다.

config.discloss 。

export default
{
  // my json here...
}

그러면...

import config from '../config.js'

는 기존 .json 파일의 Import를 허용하지 않지만 작업을 수행합니다.

안타깝게도 ES6/ES2015는 모듈 Import 구문을 통한 JSON 로드를 지원하지 않습니다.근데...

당신이 그것을 할 수 있는 방법은 여러 가지가 있다. JavaScriptJavaScript)에서 수 .window.FileReader브라우저에서 실행 중인 경우 옵션이 될 수 있습니다.또는 다른 질문(NodeJs를 사용하는 경우)에서 설명한 대로 다른 로더를 사용할 수도 있습니다.

IMO의 가장 간단한 방법은 JSON을 JS 오브젝트로 ES6 모듈에 삽입하여 내보내는 것입니다.그러면 필요한 곳에 Import할 수 있습니다.

또, Web 팩을 사용하고 있는 경우는, 디폴트로 JSON 파일을 Import 할 수 있습니다(이후,webpack >= v2.0.0를 참조해 주세요.

import config from '../config.json';

노드를 사용하는 경우 다음을 수행할 수 있습니다.

const fs = require('fs');

const { config } = JSON.parse(fs.readFileSync('../config.json'));

또는

const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');

기타:

// config.js
{
// json object here
}

// script.js

import { config } from '../config.js';

또는

import * from '../config.json'

babel+browserify를 사용하고 있으며 ./i18n/locale-en.json 디렉토리에 변환 네임스페이스가 있는 JSON 파일이 있습니다(ngTranslate에서 사용).

JSON 파일에서 아무것도 내보낼 필요 없이(BTW는 불가능), 다음 구문을 사용하여 콘텐츠를 기본 Import할 수 있습니다.

import translationsJSON from './i18n/locale-en';

및에 따라서는 JSON 할 수 .default

import { default as config } from '../config.json';

: : 부내사 within within 。Next.js

fetch가 있는 브라우저(기본적으로 현재 모두):

수 요.importJSON MIME 유형의 파일, JavaScript MIME 유형의 파일만.향후 추가되는 기능(공식 논의)일 수 있습니다.

fetch('./file.json')
  .then(response => response.json())
  .then(obj => console.log(obj))

Node.js v13.2+의 경우:

현재 플래그가 필요합니다.플래그가 없으면 기본적으로 지원되지 않습니다.

실행해 보다

node --input-type module --experimental-json-modules --eval "import obj from './file.json'; console.log(obj)"

콘솔로 출력되는obj 콘텐츠를 참조해 주세요.

JSON 모듈과 Import Assertions를 제안하고 구현해 주신 모든 분들께 감사드립니다.Chrome 91에서는 다음과 같이 JSON을 직접 가져올 수 있습니다.

// test.json
{
    "hello": "world"
}

// Static Import
import json from "./test.json" assert { type: "json" };
console.log(json.hello);

// Dynamic Import
const { default: json } = await import("./test.json", { assert: { type: "json" } });
console.log(json.hello);

// Dynamic Import
import("./test.json", { assert: { type: "json" } })
  .then(module => console.log(module.default.hello));

주의: 현재 다른 브라우저에서는 아직 이 기능을 구현하지 못할 수 있습니다.

조금 늦었지만, 패키지에 기반한 앱 버전 전송과 관련된 웹 앱 분석을 제공하려다 우연히 같은 문제를 발견했습니다.json 버전

설정은 다음과 같습니다.반응 + 환원, Webpack 3.5.6

webpack 2+ 이후 json-loader가 잘 작동하지 않아 만지작거리다가 결국 제거되었습니다.

실제로 효과가 있었던 솔루션은 단순히 fetch를 사용하는 것이었습니다.이것은 비동기 접근법에 적응하기 위해 일부 코드 변경을 강제할 가능성이 높지만, 특히 fetch가 즉시 json 디코딩을 제공한다는 사실을 고려할 때 완벽하게 작동했습니다.

여기 있습니다.

  fetch('../../package.json')
  .then(resp => resp.json())
  .then((packageJson) => {
    console.log(packageJson.version);
  });

소포에 대해 얘기했으니까 명심하세요.특히 여기서 파일은 일반적으로 프로덕션 빌드(또는 개발)에 번들되지 않습니다.따라서 CopyWebpackPlugin을 사용하여 fetch를 사용할 때 파일에 액세스할 수 있어야 합니다.

간단하게 다음 작업을 수행합니다.

import * as importedConfig from '../config.json';

그런 다음 다음과 같이 사용합니다.

const config = importedConfig.default;

답변과 Node에서는 Node.js를 사용할 수 .requireES 모듈 내에서도 JSON 파일을 읽을 수 있습니다.이것은 다른 패키지 내의 파일을 읽을 때 특히 유용하다는 것을 알게 되었습니다.이는 노드 자체의 모듈 해상도 전략을 이용하여 파일을 찾기 때문입니다.

requireES 모듈의 경우 먼저 로 작성해야 합니다.

다음으로 완전한 예를 제시하겠습니다.

import { createRequire } from 'module';

const require = createRequire(import.meta.url);
const packageJson = require('typescript/package.json');
console.log(`You have TypeScript version ${packageJson.version} installed.`);

TypeScript가 설치된 프로젝트에서는 위의 코드가 package.json에서 TypeScript 버전 번호를 읽고 인쇄합니다.

경우 NodeJS v12 " "--experimental-json-modules바벨의 도움 없이 그 묘기를 부릴 수 있을 거야.

https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules

, commonjs는 commonjs 형식으로 Import됩니다.import { a, b } from 'c.json'는 아직 지원되지 않습니다.

단, 다음과 같은 작업을 수행할 수 있습니다.

import c from 'c.json';
const { a, b } = c;

".resource.json"에서 데이터를 가져올 수 있습니다. 이제 JSON 모듈이 지원됩니다.이를 통해 개발자는 동적으로 취득하는 fetch() 함수에 의존하지 않고 JSON을 정적으로 Import할 수 있습니다.

https://www.stefanjudis.com/snippets/how-to-import-json-files-in-es-modules/

보다 우아한 해결책은 Common을 사용하는 것입니다.JS 필요 함수

createRequire 공통 구축 필요JS에는 일반적인 공통을 사용할 수 있도록 함수가 필요합니다.JSON 읽기 등의 JS 기능

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");

JSON 파일 가져오기는 아직 실험 단계입니다.아래 플래그를 통해 지원할 수 있습니다.

--experimental-json-moderic

않으면 할 수 .import.meta.urlfs 링크:-

import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));

쓸 수 요.module.createRequire()

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');

"babel-plugin-inline-json-import" 플러그인을 설치하고 .balberc에서 플러그인을 추가합니다.

  1. 플러그인 설치

    npm install --save-dev babel-syslog-json-import

  2. babelrc 구성 플러그인

    "filename" : ["filen-json-import""]

그리고 이게 내가 사용하는 코드야

import es from './es.json'
import en from './en.json'

export const dictionary = { es, en }

사용하고 있다

  • vuej, 버전: 2.6.12
  • vuex, 버전: 3.6.0
  • vuex-i18n, 버전: 1.13.1

솔루션은 다음과 같습니다.

messages.messages:

import Vue from 'vue'
import Vuex from 'vuex';
import vuexI18n from 'vuex-i18n';
import translationsPl from './messages_pl'
import translationsEn from './messages_en'

Vue.use(Vuex);

export const messages = new Vuex.Store();

Vue.use(vuexI18n.plugin, messages);

Vue.i18n.add('en', translationsEn);
Vue.i18n.add('pl', translationsPl);

Vue.i18n.set('pl');

messages_pl.json:

{
    "loadingSpinner.text:"Ładowanie..."
}

messages_en.json:

{
    "loadingSpinner.default.text":"Loading..."
}

메이저

import {messages} from './i18n/messages'
Vue.use(messages);

let filePath = '../../data/my-file.json'

let arrayImport = await import(filePath, {
  assert: { type: "json" },
});
const inputArray = arrayImport.default 

console.log('result', inputArray)

상세한 것에 대하여는, 여기를 참조해 주세요.v8 - Dynamic import()

Azad에서 설명한 바와 같이 정답은 fs.readFileSync()를 사용하여 파일을 로드하고 (또는 fs.readFile with callback, fs.promes.readFile with promits/ait 등의 비동기식 배리언트 중 하나), JSON을 JSON.parse()로 해석하는 것입니다.

const packageJsonRaw = fs.readFileSync('location/to/package.json' ) 
const packageJson = JSON.parse(packageJsonRaw )

웹 팩/바벨 옵션은 해당 설정을 사용하지 않는 한 실용적이지 않습니다.

ES6 Modules 구문을 사용하고 있으므로 type Atribute가 module로 설정되어 있는지 확인하십시오.

index.js 파일에 JSON 파일을 Import하는 방법은 다음과 같습니다.

import myJson from './example.json' assert {type: 'json'};

ECMAScript 6에서 JSON 파일 가져오기

import myJson from './example.json' assert {type: 'json'};

https://www.stefanjudis.com/snippets/how-to-import-json-files-in-es-modules-node-js/

ES 모듈은 Node.js 랜드에서는 아직 상당히 새로운 모듈입니다(Node 14 이후 안정적입니다).모듈에는 모듈시스템이 내장되어 있어 톱레벨 등의 기능이 대기하고 있습니다.

Pawel Grzybek의 ES 모듈에 관한 유익한 글을 읽었는데, 오늘 ES 모듈에서는 JSON 파일을 Import할 수 없다는 것을 알게 되었습니다.

import info from `./package.json` assert { type: `json` };


const { default: info } = await import("./package.json", {
  assert: {
    type: "json",
  },
});

너무 아쉬워요. ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★require음음 such const data = require('./some-file.json')Node.js는 Node.js를 사용합니다.

그러나 현재 Node.js에서 Import Assertions를 사용할 수 있습니까?

기입 시 현재 Node.js LTS(v18.12)는 Import 어사션을 실험적인 것으로 마크하고 있습니다.

은 어떻게 해야 하는지에 설명하고 있습니다.JSONES 모듈에서는 아직 실험 기능을 사용하지 않을 수 있습니다.

옵션 1: JSON 파일을 직접 읽고 해석합니다.

Node에서는 Node.js를 .fs파일을 읽고 해석하는 작업을 직접 수행합니다.

import { readFile } from 'fs/promises';
const json = JSON.parse(
  await readFile(
    new URL('./some-file.json', import.meta.url)
  )
);

옵션 2: 공통 활용JSrequireJSON 파일을 로드하는 함수

이 문서에는 JSON 파일을 로드하는 데 사용할 수 있는 것도 기재되어 있습니다.이 접근방식은 Pawel이 블로그 투고에서 조언하는 방식이다.

createRequire공통을 구축할 수 있습니다.JSrequire일반적인 공통을 사용하는 함수JS 기능(Node.js EcmaScript 모듈의 JSON 읽기 등).

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");

json 확장자를 가진 파일 구조는 데이터 전송에 사용되며, fetch 명령을 사용하여 요청을 전송하여 json 파일 데이터를 로컬로 검색할 수 있습니다.

다음 예제에서는 count.json 파일의 데이터를 수신합니다.

// count.json

fetch("./count.json") 
.then((response) => { return response.json(); }) 
.then((data) => console.log(data));

언급URL : https://stackoverflow.com/questions/34944099/how-to-import-a-json-file-in-ecmascript-6