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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With