简体   繁体   中英

VueJS compile failing when importing json data

I'm trying to import a static .json file in the <script> section of a .Vue file like so import Test from '@assets/test.json'

Based on what I've read about webpack, this should work out of the box. I've also tried explicitly defining both the .json extension in webpack resolve and the json loader under loaders.

However, for me it fails with the error:

ERROR  Failed to compile with 1 errors                                                                                                                                                                                                     9:14:24 AM

This dependency was not found:

* @assets/test.json in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Settings.vue?vue&type=script&lang=js&

To install it, you can run: npm install --save @assets/test.json

That seems to be strange as it's not a dependency I'd be able to install?

My test.json file just contains {} , but I've also tried it with the real data file and the same outcome.

Thanks in advance for any help.

Edit: Thanks to @tao for helping me figure it out on chat. The error was indeed trivial: import Test from '@assets/test.json' should have been import Test from '@/assets/test.json'

For typescript support you have to add

"resolveJsonModule": true,

to compilerOptions in tsconfig.json .

And add

declare module '*.json' {
  const value: unknown;
  export default value;
}

to your shims-vue.d.ts


In Javascript, you don't need to do anything special. This should work:

test.json :

{
  "foo": "bar"
}

Your *.vue SFC file:

<script>
import * as json from './test.json';

export default {
  data: () => ({
    json
  }),
  mounted() {
    console.log(this.json)
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM