1

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.

2
  • Are you sure your tree.json file and your App.vue file are in the same folder? Commented Jan 15, 2019 at 16:34
  • you should be able to import without .json extension, permitted that the file is on the same folder (same comment as above) Commented Jan 15, 2019 at 16:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Wow! - I follow you on youtube! - :D - keep up the good work!
I know that webpack is supposed to handle json files and it does. As stated in the question, I'm able to load the json file from a vanilla .js file instead of from a .vue file.
Did you add .json to your webpack resolve extensions?
I had a feeling :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.