使用ES6语法和动态路径导入模块 [英] Importing modules using ES6 syntax and dynamic path

查看:1556
本文介绍了使用ES6语法和动态路径导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做:

 从'./../app.js'导入应用程序; 

但这不是:

 从path.join导入应用程序(process.cwd(),'app'); 

我正在获取:

  SyntaxError:/path/file.js:意外的令牌(5:16)
> 5 |从path.join(process.cwd(),'app')导入应用程序;
| ^

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

解决方案

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



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

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).

解决方案

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

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 app identifier in your module scope however (and cannot reexport it), it typically would only be available in a callback or so.

这篇关于使用ES6语法和动态路径导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆