有没有办法将导入/需要在JavaScript中的一行中合并?
我在一个项目中有许多不同的模块,每个模块都有其自己的文件夹,每个模块在每个模块中,有3个文件:
- index.js
- index.test.js
- data.js
每个模块都有这些文件,相同的文件名和不同的内容。
对于index.test.js文件,所有模块中的所有index.test.js文件的导入语句都是相同的,如下所示:
const runAnalysis = require('./index');
const { data } = require('./data');
const { formatData } = require('utils');
const formattedData = formatData(data);
由于所有index.test.js文件都是相同的一种将它们合并为一行的方法,因此在每个模块中不必一遍又一遍地重复它?
有没有办法将这些导入语句放入标题文件中,然后每个index.test.js可以只是导入标头文件?
I have many different modules in a project, each module has it's own folder, within each module, there are 3 files:
- index.js
- index.test.js
- data.js
Every module has these files, same file names and different content.
For the index.test.js files, the import statements are all the same for all index.test.js files in all modules, look like this:
const runAnalysis = require('./index');
const { data } = require('./data');
const { formatData } = require('utils');
const formattedData = formatData(data);
Since these import statements are the same for all index.test.js files, is there a way to consolidate these into one line, so it doesn't have to be repeated over and over in every module?
Is there a way to put these import statements in a header file, and then each index.test.js can just import the header file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定这是有效的还是建议的,但可以起作用。
创建一个UTIL JS文件,它可以在项目root Directory上生存,让我们使用以下代码命名IT IMPORT-UTIL.JS。
然后,可以这样使用此文件来获取
runAnalysis
和fordatteddata
__ dirname
是使其工作的诀窍,它为目录提供了目录路径要导入的index.js和data.js。现在可以在每个模块文件夹中使用此单行,给定文件夹包含index.js和data.js,它的工作原理与以下4行代码相同。
Not sure if this is efficient or recommended, but it works.
Create a util js file and it can live at the project root directory, let's name it import-util.js with the following code.
Then this file can be used like this to get the
runAnalysis
andformattedData
__dirname
is the trick to make it work, it provides the directory path for the index.js and data.js to be imported.This single line can now be used in every module folder, given the folder contains the index.js and data.js, it works the same as the following 4 lines of code.