Can module import path issues be solved during Webpack compilation?
P粉231079976
P粉231079976 2023-08-26 18:08:57
0
1
381
<p>I want to create a build that only includes specific components in the bundle based on environment variables. </p> <p>For example, when I import the component like this: </p> <pre class="brush:php;toolbar:false;">import Module1 from '@/components/Module1'</pre> <p>I want the path to actually be transformed so that the import looks like this: </p> <pre class="brush:php;toolbar:false;">import Module1 from '@/components/brands/' process.env.APP_BRAND 'Module1'</pre> <p>Now, I don't want to do this for all imports, but only for specific imports (e.g. modules with branded versions), so maybe I want to prepend the import path with something like < code>!brand!</code>, which will be the indicator to apply the path transformation. Therefore, the above logic should only be executed for the following import paths: </p> <pre class="brush:php;toolbar:false;">import Module1 from '!brand!@/components/Module1'</pre> <p>If <code>process.env.APP_BRAND</code> is false, then I just want to keep the original import (e.g. just remove the <code>!brand!</code> prefix from the path ). </p> <p>So the important point is that I want this to be done at build time so that Webpack can statically analyze the module and create an optimized build. Is this feasible? I think I need to add this path conversion logic somehow, but how should I do it? Should I create a loader, plugin or is there a ready-made solution? </p> <p>I'm using Webpack 5. </p>
P粉231079976
P粉231079976

reply all(1)
P粉714844743

Webpack provides a module resolve function that you can use here. Read the documentationhere. For example, in your case you could do this:

const path = require('path');

module.exports = {
  resolve: {
    alias: {
      '@/components/Module1': path.join(
        __dirname,
        process.env.APP_BRAND
          ? '@/components/brands/' + process.env.APP_BRAND + 'Module1'
          : '@/components/Module1')
    }
  },
};

Please note that here you need to pass environment variables to your Webpack process (that is, the Node.js process) and make decisions based on this. In addition, your resolve module must be absolute path.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!