英文:
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),
},
},
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论