我如何在ES6中需要一个目录?

时间:2021-07-05 20:26:10

I know I can require a file in ES6 like this:

我知道我可以在ES6中要求这样的文件:

require('./config/auth');

When I try to do this

当我尝试这样做

require('./config/');

I get: Module not found: Error: Cannot resolve directory './config'. Why does this happen? How can I require a directory?

我得到:找不到模块:错误:无法解析目录'./config'。为什么会这样?我怎么能要求目录?

2 个解决方案

#1


First of all, your requires are in NodeJS/io.js syntax, module in ES6 syntax looks like this:

首先,您的需求是NodeJS / io.js语法,ES6语法中的模块如下所示:

import "./config/auth";

Or if you want to load something from it:

或者如果你想从中加载一些东西:

import authenticate from "./config/auth";

You can't load whole directories at once, but in Node/io.js you can create a module and then load that.

您无法一次加载整个目录,但在Node / io.js中,您可以创建一个模块然后加载它。

Note that as a workaround you can load a single file that in turn loads multiple files and returns their results. There is also work in progress on an asynchronous loader but that changes so often it's hard to keep track so I wouldn't rely on it just yet.

请注意,作为一种变通方法,您可以加载单个文件,该文件又会加载多个文件并返回其结果。异步加载器上还有一些工作正在进行中,但是这种情况经常发生变化很难跟踪,所以我不会依赖它。

#2


I personally use a package called require-dir. This should work for you:

我个人使用一个名为require-dir的包。这应该适合你:

import requireDir from 'require-dir';
requireDir('./config');

#1


First of all, your requires are in NodeJS/io.js syntax, module in ES6 syntax looks like this:

首先,您的需求是NodeJS / io.js语法,ES6语法中的模块如下所示:

import "./config/auth";

Or if you want to load something from it:

或者如果你想从中加载一些东西:

import authenticate from "./config/auth";

You can't load whole directories at once, but in Node/io.js you can create a module and then load that.

您无法一次加载整个目录,但在Node / io.js中,您可以创建一个模块然后加载它。

Note that as a workaround you can load a single file that in turn loads multiple files and returns their results. There is also work in progress on an asynchronous loader but that changes so often it's hard to keep track so I wouldn't rely on it just yet.

请注意,作为一种变通方法,您可以加载单个文件,该文件又会加载多个文件并返回其结果。异步加载器上还有一些工作正在进行中,但是这种情况经常发生变化很难跟踪,所以我不会依赖它。

#2


I personally use a package called require-dir. This should work for you:

我个人使用一个名为require-dir的包。这应该适合你:

import requireDir from 'require-dir';
requireDir('./config');