Not able to import json file in ionic2 rc2


#1

I want to import a json file in my Ionic2 project. In my home.ts file I have

import * as data from ‘json!../…/assets/i18n/en.json’;

In my declarations.d.ts in the src folder, I have:

declare module ‘json!*’ {
const value: any;
export default value;
}

“ionic serve” does not spit any error. However, the chrome dev tools console window gives the following error and the page does not load.

Uncaught Error: Cannot find module “json!../…/assets/i18n/en.json”(…)

Here is my ionic info.

C:\Users\ccc\Documents\Projects\Bus-DriverApp-Tabs>ionic info

Your system information:

ordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.8
Ionic App Lib Version: 2.1.4
Ionic App Scripts Version: 0.0.45
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 7 Node Version: v6.9.1
Xcode version: Not installed

I have google searched around, but could not solve it.


#2

Finally I figured it out. I need to provide a customized webpack.config.js file to override the loaders section in the default webpack.config.js file. My customized webpack.config.js looks like the following:

var path = require(‘path’);
module.exports = {
module: {
loaders: [
{
test: /.json$/,
include: [path.resolve(__dirname, “src”)],
loader: ‘json’
}
].concat(getSourcemapLoader())
}
}

function getSourcemapLoader() {
if (process.env.IONIC_ENV === ‘prod’) {
// TODO figure out the disk loader, it’s not working yet
return [];
}

return [
{
test: /.ts$/,
loader: path.join(process.env.IONIC_APP_SCRIPTS_DIR, ‘dist’, ‘webpack’, ‘typescript-sourcemap-loader-memory.js’)
}
];
}

In particular, I need the include path configured. Also it seems the loader: “json” configuration does not have any effect either in my customized config file or the default config file. As a result, I need to do

import data from ‘json-loader!../…/assets/i18n/en.json’;

in my home.ts file.

And in declarations.d.ts file, add the following:

declare module ‘*.json’ {
let json: any;
export default json;
}