Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack. Theming fallback

Tags:

webpack

Is it possible to resolve theming path as fallback with webpack?

So let's say I have next structure:

    app/
    ├── componentA/
    │   └─ index.js
    │
    └── themes/
        └── woot/
            └── componentA/
                └── index.js

And I do import

    import ComponentA from 'app/componentA/index.js';

Then depending on build I want to receive next:

  1. for webpackapp/componentA/index.js
  2. for THEME="woot" webpackapp/themes/woot/componentA/index.js

Thank you

like image 636
gotbahn Avatar asked Aug 20 '17 07:08

gotbahn


People also ask

For which file types webpack doesn't require additional loaders?

Webpack can understand JavaScript and JSON files only. To handle files other than that loaders can be used. As Webpack treats everything (JavaScript, images, CSS, HTML...) as a module, the loader transform modules.

How do webpack loaders work?

A loader in webpack is a function that transforms a source code of imported modules. Loaders are the heart and soul of how webpack compiles TypeScript to JavaScript, turns SASS into CSS, and JSX into React. createElement calls. In fact, webpack doesn't really do all that, loaders do!

Which package is used to add the initial packages of webpack?

We can use webpack as a value of one of the commands in our package. json file — without any flag. This way, webpack will assume your project's entry point file lives in the src directory. It will bundle the entry file and output it to the dist directory.


1 Answers

It should be something like that... I didn't test, but I think it could represent a good starting point.

look at NormalModuleReplacementPlugin

// webpack.config.js
module.exports = env => {
  const theme = env.theme || null;

  const configs = Object.create(null);

  configs.plugins = [];

  if(theme) {
    const theming = new webpack.NormalModuleReplacementPlugin(
    /(.*)Components\/index/, (resource) => {

        resource.request = resource
          .request
          .replace(/Components\/index/, `Components\/${theme}\/index`);
      }
  );

    configs.plugins.push(theming);
  }

  return Promise
    .resolve(config)
  ;
}

// package.json
{
  "scripts": {
    "webpack": "webpack --config webpack.config.js"
  }
}

// cli
npm run webpack -- --env.theme=Dark
like image 91
Hitmands Avatar answered Sep 28 '22 06:09

Hitmands