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

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

问题描述

这有效:

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

但这不会:

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

我得到:

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

推荐答案

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

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.

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

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天全站免登陆