node.js 中的 ES6 变量导入名称?

ES6 variable import name in node.js?

是否可以在使用 ES6 导入时将某些内容导入到提供变量名的模块中?

即我想根据配置中提供的值在运行时导入一些模块:

import something from './utils/' + variableName;

不适用于 import 语句。 importexport 以可静态分析的方式定义,因此它们不能依赖于运行时信息。

您正在寻找 loader API (polyfill),但我对规范的状态有点不清楚:

System.import('./utils/' + variableName).then(function(m) {
  console.log(m);
});

除了, I'll note explicitly that this is not currently allowed by the ECMAScript 6 grammar

ImportDeclaration :

  • import ImportClause FromClause ;

  • import ModuleSpecifier ;

FromClause :

  • from ModuleSpecifier

ModuleSpecifier :

  • StringLiteral

A ModuleSpecifier 只能是 StringLiteral,不能是任何其他类型的表达式,例如 A​​dditiveExpression[=19] =].

虽然这实际上不是动态导入(例如,在我的情况下,我在下面导入的所有文件都将由 webpack 导入和捆绑,而不是在运行时选择),但我一直在使用的模式可能在某些情况下协助是:

import Template1 from './Template1.js';
import Template2 from './Template2.js';

const templates = {
  Template1,
  Template2
};

export function getTemplate (name) {
  return templates[name];
}

或者:

// index.js
export { default as Template1 } from './Template1';
export { default as Template2 } from './Template2';


// OtherComponent.js
import * as templates from './index.js'
...
// handy to be able to fall back to a default!
return templates[name] || templates.Template1;

我认为我无法像使用 require() 那样轻松地恢复到默认设置,如果我尝试导入不存在的构造模板路径,则会引发错误。

可以在此处找到 require 和 import 之间的良好示例和比较:http://www.2ality.com/2014/09/es6-modules-final.html

关于从@iainastacio 重新导出的优秀文档: http://exploringjs.com/es6/ch_modules.html#sec_all-exporting-styles

我很想听听有关此方法的反馈:)

你可以使用非 ES6 符号来做到这一点。这对我有用:

let myModule = null;
if (needsToLoadModule) {
  myModule = require('my-module').default;
}

我不太喜欢这种语法,但它有效:
而不是写

import memberName from "path" + "fileName"; 
// this will not work!, since "path" + "fileName" need to be string literal

使用这个语法:

let memberName = require("path" + "fileName");

我会这样做

function load(filePath) {
     return () => System.import(`${filePath}.js`); 
     // Note: Change .js to your file extension
}

let A = load('./utils/' + variableName)

// Now you can use A in your module

ES 模块有一个名为 动态导入 的新规范。 基本上,您只需调用 import('./path/file.js') 就可以了。函数 returns 一个承诺,如果导入成功则用模块解析。

async function importModule() {
   try {
      const module = await import('./path/module.js');
   } catch (error) {
      console.error('import failed');
   }
}

用例

用例包括为 React、Vue 等导入基于路由的组件,以及在需要时延迟加载模块的能力在运行期间。

更多信息

这是对Google Developers的解释。

浏览器兼容性(2020 年 4 月)

根据 MDN it is supported by every current major browser (except IE) and caniuse.com 显示在全球市场份额中有 87% 的支持。同样不支持 IE 或非 chromium Edge。

我理解 Node.js 中专门针对 ES6 import 提出的问题,但以下内容可能会帮助其他人寻找更通用的解决方案:

let variableName = "es5.js";
const something = require(`./utils/${variableName}`);

请注意,如果您正在导入 ES6 模块 并且需要访问 default 导出,您将需要使用以下方法之一:

let variableName = "es6.js";

// Assigning
const defaultMethod = require(`./utils/${variableName}`).default;

// Accessing
const something = require(`./utils/${variableName}`);
something.default();

您还可以通过这种方法使用解构,这可能会让您对其他导入的语法更加熟悉:

// Destructuring 
const { someMethod } = require(`./utils/${variableName}`);    
someMethod();

不幸的是,如果您想访问 default 以及解构,您将需要分多个步骤执行此操作:

// ES6 Syntax
Import defaultMethod, { someMethod } from "const-path.js";

// Destructuring + default assignment
const something = require(`./utils/${variableName}`);

const defaultMethod = something.default;    
const { someMethod, someOtherMethod } = something;

Dynamic import()(适用于 Chrome 63+)将完成您的工作。方法如下:

let variableName = 'test.js';
let utilsPath = './utils/' + variableName;
import(utilsPath).then((module) => { module.something(); });

./utils/test.js

export default () => {
  doSomething...
}

从文件调用

const variableName = 'test';
const package = require(`./utils/${variableName}`);
package.default();

我在使用 Vue.js 时遇到了类似的问题:当您在构建时在 import(variableName) 中使用变量时,Webpack 不知道在哪里寻找。因此,您必须将其限制为具有适当扩展名的已知路径:

let something = import("@/" + variableName + ".js") 

That github 对同一问题的回答对我很有帮助。