简体   繁体   中英

How to include static files in a Node module and still make it available when used with webpack

I have two packages A and B. A is a general-purpose module, useful for eg both Node and browser. B is a project specific for the browser environment and it requires A, and uses Webpack.

A has example.json , which is read inside of the the files of A as

const {readFileSync} require('fs');
const {join: joinPath} require('path');
function getExample() {
    return readFileSync(joinPath(__dir, 'path/to/example.json'));
}

Inside package B, I would like to call getExample() but naturally the fs package is not available on the browser.

What kind of architecture should I rather use for this use case? Maybe (a) maybe I can Webpack ify project A. Or maybe I need some particular Webpack configuration for project B?

I'm fairly familiar with Node development but when it comes to the browser environment or Webpack, I'm totally lost!

As implied by mfarhadpur , you can just require('./your/json/file) in Node. That is, require can handle not only .js files but also .json files.

This removes altogether the need for using fs in my use case.

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