Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
    });
};

I tried in my webpack.config.js this:

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

Project structure:

dist
  content
     json
        menu.json <- this is missing

src
  content
     json
       menu.json <- source file

Question:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

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';

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 is the same JavaScript object that you would get from your getMenu function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...