Rami Chasygov
Rami Chasygov

Reputation: 2784

Inject varables in css, html, js with Webpack

I have problem, that in my project I use constants, variables in css, html, js and if I wanna something change some constants I need find it in html or css or js, that take long time. And wonder if it possible have separate js file with variables and constants, and inject value from that to html, js, css (sass). Pseudocode below. I wanna know, is even possible do with webpack, if yes, how or where I should look?

document.getElementById(${=name}).style.color = 'white';
.box {
  width: ${=width}
}
<div class="box box_${=id}">
  Some text
</div>

const css = {
  width: '250px',
};

const html = {
  id: '2'
};

const js = {
  id: 'haha',
};

Upvotes: 0

Views: 111

Answers (1)

ben
ben

Reputation: 3568

You can use a webpack plugin for doing all replacement. for instance: https://github.com/jamesandersen/string-replace-webpack-plugin

It can replace in any files you want...

for JS (for instance) you would have something like:

module: {
  loaders: [
     // configure replacements for file patterns
     { 
        test: /.js$/,
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /DEFAULT_WIDTH/ig,
                    replacement: function () {
                        return '100px';
                    }
                }
            ]})
        }
  ]
},

Upvotes: 2

Related Questions