在Webpack中加载静态JSON文件

在Webpack中加载静态JSON文件

本文介绍了在Webpack中加载静态JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一些构造:

I have somewhere in my code following construction:

var getMenu = function () {
    return window.fetch("portal/content/json/menu.json").then(function (data) {
        return data.json();
    });
};

我试过我的 webpack.config.js 这个:

module: {
    loaders: [
        ...
        {
            test: /\.json$/,
            exclude: /node_modules/,
            use: [
                'file-loader?name=[name].[ext]&outputPath=portal/content/json'
            ]
        },
        ...
   ]
}

项目结构

dist
  content
     json
        menu.json <- this is missing

src
  content
     json
       menu.json <- source file

问题:

webpack如何将 src / content / json / menu.json 复制到 dist / content / json / menu.json

How can webpack copy src/content/json/menu.json to dist/content/json/menu.json ?

推荐答案

您正在使用 fetch 请求JSON文件和这只会在运行时发生。此外,webpack仅处理导入的任何内容。你希望它处理一个函数的参数,但是如果webpack这样做,函数的每个参数都会被认为是一个模块,并且会打破该函数的任何其他用途。

You're using fetch to request a JSON file and that will only happen at runtime. Furthermore, webpack only processes anything that is imported. You expected it to handle an argument to a function, but if webpack did that, every argument to a function would be considered a module and that breaks any other use for that function.

如果你想让你的装载机开始,你可以导入文件。

If you want your loaders to kick in, you can import the file.

import './portal/content/json/menu.json';

您还可以导入JSON并直接使用它而不是在运行时获取它。 Webpack 2使用默认情况下,所有 .json 文件。您应该删除 .json 规则,然后按如下方式导入JSON。

You can also import the JSON and use it directly instead of fetching it a runtime. Webpack 2 uses json-loader by default for all .json files. You should remove the .json rule and you would import the JSON as follows.

import menu from './portal/content/json/menu.json';

menu 与您的JavaScript对象相同将来自你的 getMenu 函数。

menu is the same JavaScript object that you would get from your getMenu function.

这篇关于在Webpack中加载静态JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:48