ES6 모듈 구현, json 파일 로드 방법
https://github.com/moroshko/react-autosuggest의 예를 구현하고 있습니다.
중요한 코드는 다음과 같습니다.
import React, { Component } from 'react';
import suburbs from 'json!../suburbs.json';
function getSuggestions(input, callback) {
const suggestions = suburbs
.filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))
.sort((suburbObj1, suburbObj2) =>
suburbObj1.suburb.toLowerCase().indexOf(lowercasedInput) -
suburbObj2.suburb.toLowerCase().indexOf(lowercasedInput)
)
.slice(0, 7)
.map(suburbObj => suburbObj.suburb);
// 'suggestions' will be an array of strings, e.g.:
// ['Mentone', 'Mill Park', 'Mordialloc']
setTimeout(() => callback(null, suggestions), 300);
}
이 예제의 복사 붙여넣기 코드(작동)에, 프로젝트에 에러가 있습니다.
Error: Cannot resolve module 'json' in /home/juanda/redux-pruebas/components
프리픽스 json을 삭제했을 경우:
import suburbs from '../suburbs.json';
이렇게 하면 컴파일 시 오류가 발생하지 않습니다(가져오기 완료).그러나 실행 시 오류가 발생했습니다.
Uncaught TypeError: _jsonfilesSuburbsJson2.default.filter is not a function
디버깅을 하면 교외가 배열이 아닌 객체인 것을 알 수 있으므로 필터 함수는 정의되어 있지 않습니다.
단, 주석 첨부 예에서는 제안이 배열입니다.다음과 같이 제안을 다시 작성하면 모든 것이 작동합니다.
const suggestions = suburbs
var suggestions = [ {
'suburb': 'Abbeyard',
'postcode': '3737'
}, {
'suburb': 'Abbotsford',
'postcode': '3067'
}, {
'suburb': 'Aberfeldie',
'postcode': '3040'
} ].filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))
그럼... Import에서 어떤 json! 접두사가 사용되고 있습니까?
코드에 입력할 수 없는 이유는 무엇입니까?바벨 구성?
먼저 다음을 설치해야 합니다.
npm i json-loader --save-dev
다음으로 두 가지 방법으로 사용할 수 있습니다.
각각에 추가되는 것을 피하기 위해
import
에 추가할 수 있습니다.webpack.config
다음 행:loaders: [ { test: /\.json$/, loader: 'json-loader' }, // other loaders ]
그럼 Import
json
이런 파일import suburbs from '../suburbs.json';
에서 직접 사용
import
예를 들어 다음과 같습니다.import suburbs from 'json!../suburbs.json';
주의: 키워드 대신 입력loaders
를 사용해야 합니다. ,
또한 사용json-loader
디폴트로는
*.json 파일은 이제 json-files 없이 지원됩니다.아직 사용하실 수 있습니다.그것은 획기적인 변화가 아니다.
어레이의 경우 json-filename이 json 파일을 로드하지 않습니다.이 경우 키가 있는지 확인해야 합니다.
{
"items": [
{
"url": "https://api.github.com/repos/vmg/redcarpet/issues/598",
"repository_url": "https://api.github.com/repos/vmg/redcarpet",
"labels_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/labels{/name}",
"comments_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/comments",
"events_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/events",
"html_url": "https://github.com/vmg/redcarpet/issues/598",
"id": 199425790,
"number": 598,
"title": "Just a heads up (LINE SEPARATOR character issue)",
},
..... other items in array .....
]}
이것은 React & React Native에서만 동작합니다.
const data = require('./data/photos.json');
console.log('[-- typeof data --]', typeof data); // object
const fotos = data.xs.map(item => {
return { uri: item };
});
를 인스톨 하면, 다음의 조작을 간단하게 실시할 수 있습니다.
import suburbs from '../suburbs.json';
또는 더 간단히 말하면:
import suburbs from '../suburbs';
노드 v8.5.0+
JSON 로더는 필요 없습니다.노드는 ECMAScript 모듈(ES6 모듈 지원)과--experimental-modules
flag, 이렇게 사용할 수 있습니다.
node --experimental-modules myfile.mjs
그럼 아주 간단해
import myJSON from './myJsonFile.json';
console.log(myJSON);
그럼 변수로 묶어서myJSON
.
로딩할 수 없을 때 이 스레드를 찾았습니다.json-file
와 함께ES6 TypeScript 2.6
. 이 에러가 계속 발생하고 있습니다.
TS2307(TS) 'json-loader!' 모듈을 찾을 수 없습니다./disclosed.json'
작동시키기 위해 먼저 모듈을 신고해야 했습니다.나는 이것이 누군가를 위해 몇 시간을 절약하기를 바란다.
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import suburbs from 'json-loader!./suburbs.json';
생략하려고 하면loader
부터json-loader
에서 다음과 같은 에러가 발생했습니다.webpack
:
BRACKING CHANGE: 로더를 사용할 때 더 이상 '-loader' 접미사를 생략할 수 없습니다.'json'이 아닌 'json-syslog'를 지정해야 합니다. https://webpack.js.org/guides/migrating/ #automatic-syslog-name-syslog-syslog를 참조하십시오.
언급URL : https://stackoverflow.com/questions/33650399/es6-modules-implementation-how-to-load-a-json-file
'sourcecode' 카테고리의 다른 글
Wordpress 테마 업로드 오류 PCLZIP_ERR_BAD_포맷 (0) | 2023.02.15 |
---|---|
WordPress에 체크박스 메타박스를 저장하는 방법 (0) | 2023.02.15 |
WP_Query 또는 'get' 함수에서 반환된 워드프레스 필드 제한 (0) | 2023.02.15 |
연장기에서 단일 항목을 선택하는 방법 (0) | 2023.02.11 |
어떻게 하면 spring boot 어플리케이션에서 letsencrypt SSL 증명서를 설정하고 사용할 수 있습니까? (0) | 2023.02.11 |