ECMAScript 6에서 JSON 파일을 가져 오는 방법은 무엇입니까?
Ecmascript 6에서 json 파일에 어떻게 액세스합니까? 다음은 작동하지 않습니다.
import config from '../config.json'
JavaScript 파일을 가져 오려고하면 제대로 작동합니다.
간단한 해결 방법 :
config.js
export default
{
// my json here...
}
그때...
import config from '../config.js'
기존 .json 파일을 가져올 수는 없지만 작업을 수행합니다.
TypeScript 또는 Babel을 사용하면 코드에서 json 파일을 가져올 수 있습니다.
// Babel
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
참조 : https://hackernoon.com/import-json-into-typescript-8d465beded79
불행히도 ES6 / ES2015는 모듈 가져 오기 구문을 통한 JSON 로딩을 지원하지 않습니다. 그러나 ...
당신이 그것을 할 수있는 많은 방법이 있습니다. 필요에 따라 JavaScript로 파일을 읽는 방법을 살펴 window.FileReader
보거나 (브라우저에서 실행중인 경우 옵션 일 수 있음) 다른 질문에 설명 된대로 다른 로더를 사용할 수 있습니다 (NodeJS를 사용한다고 가정).
IMO의 가장 간단한 방법은 JSON을 JS 객체로 ES6 모듈에 넣고 내보내는 것입니다. 그렇게하면 필요한 곳으로 가져올 수 있습니다.
당신이 JSON 파일의 가져 오기, 웹팩을 사용하는 경우 또한 가치가 주목 기본적으로 작동합니다 (이후 webpack >= v2.0.0
).
import config from '../config.json';
babel + browserify를 사용하고 있으며 번역 네임 스페이스가있는 ./i18n/locale-en.json 디렉토리에 ngTranslate과 함께 사용되는 JSON 파일이 있습니다.
JSON 파일에서 아무것도 내보낼 필요없이 (btw는 불가능합니다)이 구문을 사용하여 내용을 기본적으로 가져올 수 있습니다.
import translationsJSON from './i18n/locale-en';
노드를 사용하는 경우 다음을 수행 할 수 있습니다.
const fs = require('fs');
const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time
또는
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'
빌드 도구 및 JSON 파일 내의 데이터 구조에 따라을 가져와야 할 수도 있습니다 default
.
import { default as config } from '../config.json';
예를 들어 사용 Next.js
조금 늦었지만 package.json 버전을 기반으로 앱 버전을 보내는 것과 관련된 웹 응용 프로그램에 대한 분석을 제공하는 동안 동일한 문제가 발생했습니다.
구성은 다음과 같습니다. React + Redux, Webpack 3.5.6
json-loader는 Webpack 2 이상부터 많은 작업을 수행하지 않으므로 약간의 문제를 해결 한 후 제거했습니다.
The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.
So here it is:
fetch('../../package.json')
.then(resp => resp.json())
.then((packageJson) => {
console.log(packageJson.version);
});
Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.
참고URL : https://stackoverflow.com/questions/34944099/how-to-import-a-json-file-in-ecmascript-6
'Programing' 카테고리의 다른 글
Go에서 break 문은 스위치 / 선택에서 끊어 집니까? (0) | 2020.07.17 |
---|---|
`$ HTTP_RAW_POST_DATA`가 더 이상 사용되지 않는다는 경고 (0) | 2020.07.17 |
C ++에서 코드 스 니펫의 실행 시간을 계산하는 방법 (0) | 2020.07.17 |
이동되거나 이름이 바뀐 파일에서 git diff를 수행하는 방법은 무엇입니까? (0) | 2020.07.17 |
양식이로드 된 후 코드를 어떻게 실행합니까? (0) | 2020.07.17 |