繁体   English   中英

Javascript ES6 仅从文件夹中导入一些文件

[英]Javascript ES6 import only some files from a folder

也许我完全忘记了 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),如 output 所示:

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

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM