【问题标题】:Javascript ES6 import only some files from a folderJavascript ES6 仅从文件夹中导入一些文件
【发布时间】:2020-10-16 22:01:13
【问题描述】:

也许我完全忘记了 ES6 导入/导出是如何工作的,但我希望能够做这样的事情:

import { b } from 'folder';

并且从文件夹索引文件中加载所有其他导出的文件。

这是我目前拥有的:

├── folder
│   ├── file1.js
│   ├── file2.js
│   ├── file3.js
│   └── index.js
├── test.js


//file1.js:
console.log("in file1");
export const a = 3 + 4;

//file2.js:
console.log("in file2");
export const b = 3 + 5;

//file3.js:
console.log("in file3");
export const c = 3 + 6;

//index.js:
export * from "./file1";
export * from "./file2";
export * from "./file3";

//test.js:
import { b } from "./folder";
console.log(`this is ${b}`);

问题在于,在执行此操作时,它还会加载其他两个文件(a 和 c),如输出所示:

in file1
in file2
in file3
this is 8

如何从folder导入各种文件,而无需使用特定的文件导入:

import { b } from "./folder/file2";

因为我可能需要从那个文件夹中导入很多文件,我希望我可以使用导入解构。

所以而不是:

import { b } from "./folder/file2";
import { c } from "./folder/file3";

我希望能够使用:

import { b, c } from "./folder";

但不必从文件夹中加载其他文件(在本例中为 a)。

【问题讨论】:

标签: javascript ecmascript-6 es6-modules ecmascript-2016


【解决方案1】:

How can I import various files from folder without having to use specific file import,你不能。导出是在运行时确定的,这意味着需要评估 index.js 文件以确定应该导出的内容。

但是,您可以设计您的文件,以便评估它们不会运行任何业务代码。

例如:

//file1.js:
export const Module1 = () => {
  console.log("in file1");
  return ({
    a: 3 + 4,
  });
}
//test.js
import { Module1 } from "./folder";
const { a } = Module1();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-15
    • 2015-11-25
    • 2021-04-08
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2016-05-28
    • 2020-10-12
    相关资源
    最近更新 更多