Programing

es6 모듈 구현, json 파일로드 방법

lottogame 2020. 9. 18. 19:14
반응형

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

디버그하면 교외가 배열이 아니라 objectc이므로 필터 기능이 정의되지 않은 것을 볼 수 있습니다.

그러나 예제에서 주석이 달린 제안은 배열입니다. 이와 같은 제안을 다시 작성하면 모든 것이 작동합니다.

  const suggestions = suburbs
  var suggestions = [ {
    'suburb': 'Abbeyard',
    'postcode': '3737'
  }, {
    'suburb': 'Abbotsford',
    'postcode': '3067'
  }, {
    'suburb': 'Aberfeldie',
    'postcode': '3040'
  } ].filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))

그래서 .. 무슨 json! preffix가 가져 오기에서하고 있습니까?

내 코드에 넣을 수없는 이유는 무엇입니까? 바벨 구성?


먼저 다음을 설치해야합니다 json-loader.

npm i json-loader --save-dev

그런 다음 두 가지 방법으로 사용할 수 있습니다.

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28


json-loader doesn't load json file if it's array, in this case you need to make sure it has a key, for example

{
    "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 .....
]}

This just works on 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 };
});

Found this thread when I couldn't load a json-file with ES6 TypeScript 2.6. I kept getting this error:

TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

To get it working I had to declare the module first. I hope this will save a few hours for someone.

declare module "json-loader!*" {
  let json: any;
  export default json;
}

...

import suburbs from 'json-loader!./suburbs.json';

If I tried to omit loader from json-loader I got the following error from webpack:

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed


Node v8.5.0+

You don't need JSON loader. Node provides ECMAScript Modules (ES6 Module support) with the --experimental-modules flag, you can use it like this

node --experimental-modules myfile.mjs

Then it's very simple

import myJSON from './myJsonFile.json';
console.log(myJSON);

Then you'll have it bound to the variable myJSON.


With json-loader installed, now you can simply use

import suburbs from '../suburbs.json';

or also, even more simply

import suburbs from '../suburbs';

참고URL : https://stackoverflow.com/questions/33650399/es6-modules-implementation-how-to-load-a-json-file

반응형