Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file at resolved path in Webpack

I have a node module and I want to make it compatible with webpack. I'm currently using the following pattern:

const fs = require('fs');
const someTemplate = require.resolve('./templates/template.css');

fs.readFile(someTemplate, 'utf8', (err, templateStr) => {
  // Do something with`templateStr`
});

The problem is that require.resolve will return the module id (number) instead of a path and of course doing a readFile operation on a number is going to fail.

How do I make it compatible with both node and Webpack.

like image 914
DaveJ Avatar asked Aug 04 '16 13:08

DaveJ


1 Answers

I had to dig deep to find this one.

It seems it can be solved by using some browserify plugins along with webpack.

The answer below is a copy-paste since SO does not allow links-only answers

Say you have the following Node source:

var test = require('fs').readFileSync('./test.txt', 'utf8');

After npm install transform-loader brfs --save, add the following loader to your config:

module.exports = {
    context: __dirname,
    entry: "./index.js",
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: "transform?brfs"
            }
        ]
    }
}

And here's your link: https://github.com/webpack/transform-loader#typical-brfs-example

like image 112
Tudor Ilisoi Avatar answered Sep 20 '22 08:09

Tudor Ilisoi