“Dynamic imports at build time Javascript” 可以翻译为 “构建时的动态导入 JavaScript”。

huangapple go评论56阅读模式
英文:

Dynamic imports at build time Javascript

问题

我如何在构建时根据配置静态导入特定的包?

我正在开发一个项目,该项目有多个 UI 工具包,以不同的风格提供相同的组件。每个应用程序都配置为使用特定的 UI 工具包。

JavaScript ES2020 提供动态导入:

const UIKIT= "uikit_1";

const {Component_1, Component_2} = await import(UIKIT);

然而,导入是在运行时执行的,可能比静态导入慢。由于配置不会更改,我想在构建时静态导入适当的 UI 工具包以提高性能。

我该如何实现这一点?

英文:

How can I statically import a specific package based on configuration at build time?

I am working on a project that has multiple uikits providing the same components in different styles. Each app is configured to use a specific uikit.

apps
    app_1
    app_2
packages
    uikit_1
        Component_1
        Component_2
    uikit_2
        Component_1
        Component_2

Javascript ES2020 provides dynamic imports:

const UIKIT= "uikit_1";

const {Component_1, Component_2} = await import(UIKIT);

Howerver, the import is executed in runtime so it could be slower than the static import. Since the configuration is not changing, I would like to statically import the appropriate uikit at build time to improve performance.

How can I achieve this?

答案1

得分: 3

You need to modify your build tool. For example, if you are using rollup or vite, you need read configuration in plugin and resolve placeholder in import. Actions would be different for different build tools.


example with rollup/plugin-alias

config = { 
 plugins: [
    alias({
      entries: [
       // will replace 'some/:uikit/component1' with 'some/concrete-uikit/component1' if UIKIT_DIRECTORY would be 'concrete-uikit'
       { find: ':uikit', replacement: process.env.UIKIT_DIRECTORY },
     ]
   })
 ]
}

example with webpack

module.exports = {
  //...
  resolve: {
    alias: {
      uikit: path.resolve(__dirname, process.env.UIKIT_DIRECTORY),
    },
  },
};
英文:

You need to modify your build tool. For example, if you are using rollup or vite, you need read configuration in plugin and resolve placeholder in import. Actions would be different for different build tools.


example with rollup/plugin-alias

config = { 
 plugins: [
    alias({
      entries: [
       // will replace 'some/:uikit/component1' with 'some/concrete-uikit/component1' if UIKIT_DIRECTORY would be 'concrete-uikit'
       { find: ':uikit', replacement: process.env.UIKIT_DIRECTORY },
     ]
   })
 ]
}

example with webpack

module.exports = {
  //...
  resolve: {
    alias: {
      uikit: path.resolve(__dirname, process.env.UIKIT_DIRECTORY),
    },
  },
};

huangapple
  • 本文由 发表于 2023年5月6日 16:42:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定