bernie
bernie

Reputation: 10390

How to import a json file in a Vue.js single file component with Webpack

Important

The problem was a file in the wrong directory. This will likely not help you...

The question

I'm using Vue.js single file components and want to import a .json file in one of them but I can't figure out how to do it. Here's what I want to do:

src/App.vue contains:

import data from './tree.json'; // This does not work!

export default {
  /* Component def */
};

Webpack then gives the following error:

ERROR in ./src/App.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve './tree.json' in 'C:\src'
 @ ./src/App.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=js&) 8:0-31
 @ ./src/App.vue?vue&type=script&lang=js&
 @ ./src/App.vue
 @ ./src/app.js
 @ multi ./src/app.js

Webpack configuration (simplified):

module.exports = {
  mode: 'development',

  entry: [
    './src/app.js',
  ],

  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader',
      },
      {
        test: /\.js$/,
        use: 'babel-loader',
      },
    ],
  },
};

I am using Vue.js 2.5 and Webpack 4.28.

Trying to import the same .json file in a "vanilla" .js file however does work:

// In src/app.js
import data from './tree.json';

This leads me to think there is something specific to the vue-loader that doesn't work with Webpack's native handling of .json imports, but I have no idea what.

Upvotes: 1

Views: 1818

Answers (1)

Chris Hawkes
Chris Hawkes

Reputation: 12410

The error says that it's looking for your tree.json file inside your src/ directory. If it's not there than that is your problem.

⚠️ Since webpack >= v2.0.0, importing of JSON files will work by default. You might still want to use this if you use a custom file extension. See the v1.0.0 -> v2.0.0 Migration Guide for more information

Basically, your problem has to do with the file not being in the right directory.

Upvotes: 2

Related Questions