Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing a Javascript object as a module in webpack

Inside webpack.config.js I have computed a javascript map that I'd like import as a module in the browser. I could write the data to disk and then read it back with e.g https://github.com/webpack/json-loader, but is there any more elegant ways to do this in-memory?

webpack.config:

var config = {
  key: 'data'    
}
// do something with webpack loaders

some.file.that.is.executed.in.browser.js:

var config = require('config')
window.alert('Config is', config.key)
like image 421
Juha Syrjälä Avatar asked May 16 '26 20:05

Juha Syrjälä


1 Answers

webpack loaders are file preprocessor, thus there needs to be the file that you import. So create a dummy file and use json-string-loader to override the contents.

Create an empty config.json to your project.

In webpack.config.js:

var appConfig = {
  key: 'data'
}
...
loaders: [
{
    test: /config.json$/,
    loader: 'json-string-loader?json=' + JSON.stringify(appConfig)
}

In browser:

var appConfig = require("./config.json");
// => returns {key: 'data'}
like image 196
Juha Syrjälä Avatar answered May 20 '26 22:05

Juha Syrjälä



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!