2015-11-11 23 views
69

sto implementando un esempio da https://github.com/moroshko/react-autosuggestES6 implementazione dei moduli, come caricare un file JSON

codice importante è come questo:

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); 
} 

Questo codice copia-incolla da l'esempio (che funziona) , ha un errore nel mio progetto:

Error: Cannot resolve module 'json' in /home/juanda/redux-pruebas/components 

Se prendo il preffix jSON !:

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

In questo modo non ho ricevuto errori in fase di compilazione (l'importazione è stata completata). Tuttavia ho avuto errori quando ho eseguirlo:

Uncaught TypeError: _jsonfilesSuburbsJson2.default.filter is not a function 

Se metto a punto che riesco a vedere è una periferia ObjectC, non una matrice così funzione di filtro non è definita.

Tuttavia nell'esempio i suggerimenti commentati sono un array. Se riscrivo suggerimenti come questo, tutto funziona:

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

Quindi ... che json! sta facendo il prefisso nell'importazione?

Perché non posso inserirlo nel mio codice? Qualche configurazione babel?

risposta

133

Prima di tutto è necessario installare json-loader:

npm i json-loader --save-dev 

Poi, ci sono due modi come è possibile usarlo:

  1. Al fine di evitare di aggiungere json-loader in ogni import si può aggiungi a webpack.config questa riga:

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

    Quindi importare json file come questo

    import suburbs from '../suburbs.json'; 
    
  2. Usa json-loader direttamente in import, come nel tuo esempio:

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

Nota: In webpack 2.* invece di parola chiave loaders è necessario utilizzare rules .,

anche webpack 2.* utilizza json-loader di 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

+1

grazie mille! La documentazione di json-loader mostrava effettivamente le impostazioni per webpack v2, quindi niente ha funzionato per me (usando v1!). Quindi per tutti voi là fuori, usate caricatori, non regole! Inoltre, cambia "usa" all'interno di quell'oggetto per essere "loader", proprio come questa risposta! – nbkhope

+4

Come @ alexander-t menzionato, ora puoi importare file json senza il json-loader, ma, se ti imbatti in un problema in cui il json-loader non viene riconosciuto, dovresti semplicemente aggiungere un suffisso '-loader' nei caricatori config come questo: '{test: /\.json$/, loader: 'json-loader'}' – cvetanov

+0

Perché il json importato non viene copiato in outDir se viene importato tramite dattiloscritto? – FrankerZ

10

JSON-loader non viene caricato il file JSON se si tratta di array, in questo caso, è necessario assicurarsi che ha una chiave, per esempio

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

Bello, non ci avevo pensato! –

0

Trovato questo thread quando non è stato possibile caricare un json-file con ES6 TypeScript 2.6. Ho continuato a ricevere questo errore:

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

Per farlo funzionare, ho dovuto dichiarare prima il modulo. Spero che questo salverà alcune ore per qualcuno.

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

... 

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

Se ho cercato di omettere loader da json-loader ho ottenuto il seguente errore da 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

Problemi correlati