如何使用 Webpack 在 Vue.js 单文件组件中导入 json 文件

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

重要

问题是文件在错误的目录中。这可能对您没有帮助...

问题

我正在使用 Vue.js 单文件组件,并想在其中一个组件中导入 .json 文件,但我不知道该怎么做。这是我想要做的:

src/App.vue 包含:

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

export default {
  /* Component def */
};

Webpack 然后给出以下错误:

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 配置(简化):

module.exports = {
  mode: 'development',

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

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

我正在使用 Vue.js 2.5 和 Webpack 4.28。

尝试在 "vanilla" .js 文件中导入相同的 .json 文件,但是 有效 :

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

这让我认为 vue-loader 有一些特定的东西不适用于 Webpack 对 .json 导入的本机处理,但我不知道是什么。

错误表明它正在您的 src/ 目录中寻找您的 tree.json 文件。如果它不存在,那就是你的问题。

⚠️ 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

基本上,您的问题与文件不在正确的目录中有关。