How to import json file in stencil component

1.6k views Asked by At

I want to import json file with data in StencilJS, like this:

const data = await import('./data.json')

// OR
import data from './data.json'

// OR
import * as data from './data.json'

// OR
const data = require('./data.json')

But non of these work.

What I want to achieve is to have a code-splitted, dynamically-loaded json module, or, alternatively, a statically-built json module (not code-splitted, but bundled in at certain paths).

1

There are 1 answers

1
Simon Hänisch On BEST ANSWER

Update 2/2021

It's also possible to do this without a plugin, simply by enabling resolveJsonModule in tsconfig.json (with the added bonus of inferred types).

// tsconfig.json

{
  "compilerOptions": {
    "resolveJsonModule": true,
    // ...
  }
}
import { version } from '../package.json';

(It's important to specify the .json extension in this case.)


Original Answer

You can use @rollup/plugin-json for that, which converts .json files to ES6 modules.

npm i -D @rollup/plugin-json
// stencil.config.ts

import json from '@rollup/plugin-json'

export const config: Config = {
  plugins: [json()],
  // ...
};

Then the first three of your import statements should all work, or even named imports
(like import { version } from './package').