Javascript 使用 ES6 语法和动态路径导入模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30340005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:01:22  来源:igfitidea点击:

Importing modules using ES6 syntax and dynamic path

javascriptnode.jsmoduleecmascript-6

提问by Félix Sanz

This works:

这有效:

import app from './../app.js';

But this doesn't:

但这不会:

import app from path.join(process.cwd(), 'app');

I'm Getting:

我越来越:

SyntaxError: /path/file.js: Unexpected token (5:16)
> 5 | import app from path.join(process.cwd(), 'app');
    |                 ^

It is possible (and/or how) to use "dynamic" paths? (not hardcoding the path or rely in relative paths).

可以(和/或如何)使用“动态”路径?(不硬编码路径或依赖相对路径)。

回答by Bergi

No, this is not possible. ES6 modules need to be able to statically resolve their dependencies, without executing module code, so that importstatements do work reliably. The module specifier must be a string literal.

不,这是不可能的。ES6 模块需要能够静态解析它们的依赖关系,而不需要执行模块代码,这样import语句才能可靠地工作。模块说明符必须是字符串文字。

However, the module loader of your choice should support dynamic loading of modules with variable names. You wouldn't be able to get a bound appidentifier in your module scope however (and cannot reexport it), it typically would only be available in a callback or so.

但是,您选择的模块加载器应该支持动态加载具有变量名称的模块。但是,您将无法app在模块范围内获得绑定标识符(并且无法重新导出它),它通常只能在回调中使用。

回答by loganfsmyth

ES6 imports are declarative and meant for static analysis. They cannot be dynamic.

ES6 导入是声明性的,用于静态分析。它们不能是动态的。

Generally the expectation would be that if you had some conditional imports, it would be the responsibility of the underlying path resolution logic to decide what module to load based on some static path.

通常的期望是,如果您有一些条件导入,则底层路径解析逻辑将负责根据某个静态路径决定加载哪个模块。

That or you'd use the async module loader rather than declarative imports.

或者你会使用异步模块加载器而不是声明性导入。