와일드카드를 사용하여 디렉토리 내의 모든 파일에서 모듈을 Import할 수 있습니까?
ES6에서는 다음과 같은 파일에서 여러 내보내기를 가져올 수 있습니다.
import {ThingA, ThingB, ThingC} from 'lib/things';
하지만 저는 한 파일에 한 개의 모듈을 가지고 있는 구성이 좋습니다.결국 이렇게 수입하게 됩니다.
import ThingA from 'lib/things/ThingA';
import ThingB from 'lib/things/ThingB';
import ThingC from 'lib/things/ThingC';
저는 이것을 할 수 있으면 좋겠습니다.
import {ThingA, ThingB, ThingC} from 'lib/things/*';
또는 각 파일에 하나의 기본 내보내기가 포함되어 각 모듈의 이름이 파일과 동일하다는 기존 규칙을 사용합니다.
이게 가능합니까?
이것은 불가능하다고 생각합니다만, 모듈명의 해결은 모듈로더에 달려 있기 때문에, 이것을 서포트하는 로더 실장이 있을 가능성이 있습니다.
'module file'에서 file할 수 .lib/things/index.js
그 안에 들어 있는
export * from 'ThingA';
export * from 'ThingB';
export * from 'ThingC';
그리고 그것은 당신이 할 수 있습니다.
import {ThingA, ThingB, ThingC} from 'lib/things';
이미 답변에 나와 있는 테마의 변형일 뿐이지만, 이것은 어떻습니까?
①의 Thing
,
export default function ThingA () {}
»things/index.js
,
export {default as ThingA} from './ThingA'
export {default as ThingB} from './ThingB'
export {default as ThingC} from './ThingC'
그럼 다른 곳에 있는 것들을 다 소비하려면
import * as things from './things'
things.ThingA()
아니면 몇 가지만 소비하기 위해서
import {ThingA,ThingB} from './things'
하지 않는지 저는 「이것」을 했습니다.babel
이 기능을 하는 플러그인입니다.
다음을 사용하여 설치합니다.
npm i --save-dev babel-plugin-wildcard
의 '마음', '마음', '마음', '마음'에합니다..babelrc
라이선스:
{
"plugins": ["wildcard"]
}
자세한 설치 정보는 보고서를 참조하십시오.
이를 통해 다음과 같은 작업을 수행할 수 있습니다.
import * as Things from './lib/things';
// Do whatever you want with these :D
Things.ThingA;
Things.ThingB;
Things.ThingC;
다시, repo는 정확히 무엇을 하는지 더 많은 정보를 포함하고 있지만, 이렇게 하면 생성되지 않습니다.index.js
및 하며, 컴파일 시에도 하지 않도록 합니다.readdir
행행시 。
또한 새로운 버전에서는 예시와 똑같이 수행할 수 있습니다.
import { ThingsA, ThingsB, ThingsC } from './lib/things/*';
위와 동일하게 동작합니다.
비동기 Import()를 사용할 수 있게 되었습니다.
import fs = require('fs');
그 후:
fs.readdir('./someDir', (err, files) => {
files.forEach(file => {
const module = import('./' + file).then(m =>
m.callSomeMethod();
);
// or const module = await import('file')
});
});
정말 멋진 머그리들이야!이것은 필요 이상으로 어려웠다.
플랫 기본값 1개 내보내기
이것은 스프레드를 이용할 수 있는 절호의 기회입니다....
{ ...Matters, ...Contacts }
이하에 나타냅니다.
// imports/collections/Matters.js
export default { // default export
hello: 'World',
something: 'important',
};
// imports/collections/Contacts.js
export default { // default export
hello: 'Moon',
email: 'hello@example.com',
};
// imports/collections/index.js
import Matters from './Matters'; // import default export as var 'Matters'
import Contacts from './Contacts';
export default { // default export
...Matters, // spread Matters, overwriting previous properties
...Contacts, // spread Contacts, overwriting previosu properties
};
// imports/test.js
import collections from './collections'; // import default export as 'collections'
console.log(collections);
그런 다음 명령줄에서(프로젝트 루트 /에서) babel 컴파일된 코드를 실행하려면:
$ npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
(trimmed)
$ npx babel-node --presets @babel/preset-env imports/test.js
{ hello: 'Moon',
something: 'important',
email: 'hello@example.com' }
하나의 트리형 기본값 내보내기
속성을 덮어쓰지 않으려면 다음을 변경하십시오.
// imports/collections/index.js
import Matters from './Matters'; // import default as 'Matters'
import Contacts from './Contacts';
export default { // export default
Matters,
Contacts,
};
결과는 다음과 같습니다.
$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: { hello: 'World', something: 'important' },
Contacts: { hello: 'Moon', email: 'hello@example.com' } }
여러 개의 이름 있는 내보내기(기본값 없음)
DRY 전용의 경우는, Import의 구문도 변경됩니다.
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
그러면 기본 내보내기 없이 2개의 이름 있는 내보내기가 생성됩니다.다음으로 변경:
// imports/test.js
import { Matters, Contacts } from './collections';
console.log(Matters, Contacts);
그리고 출력:
$ npx babel-node --presets @babel/preset-env imports/test.js
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello@example.com' }
명명된 모든 내보내기 가져오기
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
// imports/test.js
// Import all named exports as 'collections'
import * as collections from './collections';
console.log(collections); // interesting output
console.log(collections.Matters, collections.Contacts);
파괴에 주의해 주세요. import { Matters, Contacts } from './collections';
를 참조해 주세요.
$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: [Getter], Contacts: [Getter] }
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello@example.com' }
실제로
다음 소스 파일이 지정됩니다.
/myLib/thingA.js
/myLib/thingB.js
/myLib/thingC.js
작성/myLib/index.js
모든 파일을 묶는 것은 Import/export의 목적에 어긋납니다.index.js "wrapper files"를 통해 Import/export를 통해 모든 것을 글로벌하게 만드는 것보다 우선 모든 것을 글로벌하게 만드는 것이 더 쉽습니다.
특정 파일을 원하는 경우,import thingA from './myLib/thingA';
자신의 프로젝트에서요.
모듈 내보내기를 사용하여 "래퍼 파일"을 작성하는 것은 npm용 패키지화 또는 다년간의 복수팀 프로젝트일 경우에만 유효합니다.
여기까지 왔나?상세한 것에 대하여는, 문서를 참조해 주세요.
또한 Stackoverflow는 최종적으로 코드 펜스 마크업으로서3개의 s를 서포트하고 있습니다.
받아들여지는 답변과 비슷하지만 인덱스 파일을 작성할 때마다 새 모듈을 추가하지 않고 확장할 수 있습니다.
./modules/moduleA.js
export const example = 'example';
export const anotherExample = 'anotherExample';
./syslog/index.syslog
// require all modules on the path and with the pattern defined
const req = require.context('./', true, /.js$/);
const modules = req.keys().map(req);
// export all modules
module.exports = modules;
./disc.disc.disc.discs
import { example, anotherExample } from './modules'
여러 번 (특히 많은 파일(AST 노드 등)에 데이터를 분할하는 대규모 객체를 빌드할 때)을 사용한 적이 있습니다.이러한 스크립트를 구축하기 위해 npm에 추가하여 다른 사용자가 사용할 수 있도록 했습니다.
사용방법(현재 내보내기 파일을 사용하려면 babel을 사용해야 합니다):
$ npm install -g folder-module
$ folder-module my-cool-module/
다음을 포함하는 파일을 생성합니다.
export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc
그런 다음 파일을 사용할 수 있습니다.
import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()
@Bergi의 답변에 대한 다른 접근법일 뿐입니다.
// lib/things/index.js
import ThingA from './ThingA';
import ThingB from './ThingB';
import ThingC from './ThingC';
export default {
ThingA,
ThingB,
ThingC
}
사용하다
import {ThingA, ThingB, ThingC} from './lib/things';
웹 팩을 사용하는 경우.그러면 파일이 자동으로 Import되고 api 네임스페이스로 내보내집니다.
따라서 파일을 추가할 때마다 업데이트할 필요가 없습니다.
import camelCase from "lodash-es";
const requireModule = require.context("./", false, /\.js$/); //
const api = {};
requireModule.keys().forEach(fileName => {
if (fileName === "./index.js") return;
const moduleName = camelCase(fileName.replace(/(\.\/|\.js)/g, ""));
api[moduleName] = {
...requireModule(fileName).default
};
});
export default api;
타이프스크립트 사용자의 경우
import { camelCase } from "lodash-es"
const requireModule = require.context("./folderName", false, /\.ts$/)
interface LooseObject {
[key: string]: any
}
const api: LooseObject = {}
requireModule.keys().forEach(fileName => {
if (fileName === "./index.ts") return
const moduleName = camelCase(fileName.replace(/(\.\/|\.ts)/g, ""))
api[moduleName] = {
...requireModule(fileName).default,
}
})
export default api
노드?다음과 같이 합니다.
인덱스 파일에서 index.js를 사용하여 폴더를 만들고 다음을 추가합니다.
var GET = require('./GET');
var IS = require('./IS');
var PARSE = require('./PARSE');
module.exports = { ...GET, ...IS, ...PARSE};
파일 GET.js 또는 IS.js에서는 정상적으로 내보냅니다.
module.exports = { /* something as you like */}
이제 index.js만 포함하면 됩니다.
const Helper = require('./YourFolder');
도우미는 모든 기능을 YourFolder에 포함합니다.
안녕하세요!
이것은 당신이 요구한 것은 아니지만, 이 방법으로 반복할 수 있습니다.componentsList
다른 파일에 저장하여 다음과 같은 기능을 사용합니다.componentsList.map(...)
꽤 유용하다고 생각합니다!
import StepOne from './StepOne';
import StepTwo from './StepTwo';
import StepThree from './StepThree';
import StepFour from './StepFour';
import StepFive from './StepFive';
import StepSix from './StepSix';
import StepSeven from './StepSeven';
import StepEight from './StepEight';
const componentsList= () => [
{ component: StepOne(), key: 'step1' },
{ component: StepTwo(), key: 'step2' },
{ component: StepThree(), key: 'step3' },
{ component: StepFour(), key: 'step4' },
{ component: StepFive(), key: 'step5' },
{ component: StepSix(), key: 'step6' },
{ component: StepSeven(), key: 'step7' },
{ component: StepEight(), key: 'step8' }
];
export default componentsList;
require도 사용할 수 있습니다.
const moduleHolder = []
function loadModules(path) {
let stat = fs.lstatSync(path)
if (stat.isDirectory()) {
// we have a directory: do a tree walk
const files = fs.readdirSync(path)
let f,
l = files.length
for (var i = 0; i < l; i++) {
f = pathModule.join(path, files[i])
loadModules(f)
}
} else {
// we have a file: load it
var controller = require(path)
moduleHolder.push(controller)
}
}
그런 다음 모듈을 사용합니다.동적으로 로드된 컨트롤러가 있는 홀더:
loadModules(DIR)
for (const controller of moduleHolder) {
controller(app, db)
}
사용자 atilkan의 접근 방식을 참고하여 조금 수정할 수 있었습니다.
타이프스크립트 사용자의 경우
require.context('@/folder/with/modules', false, /\.ts$/).keys().forEach((fileName => {
import('@/folder/with/modules' + fileName).then((mod) => {
(window as any)[fileName] = mod[fileName];
const module = new (window as any)[fileName]();
// use module
});
}));
기본값을 A, B, C로 내보내지 않고 {}만 내보내면 가능합니다.
// things/A.js
export function A() {}
// things/B.js
export function B() {}
// things/C.js
export function C() {}
// foo.js
import * as Foo from ./thing
Foo.A()
Foo.B()
Foo.C()
언급URL : https://stackoverflow.com/questions/29722270/is-it-possible-to-import-modules-from-all-files-in-a-directory-using-a-wildcard
'sourcecode' 카테고리의 다른 글
문자열 검사기, 파일 이름 (0) | 2023.01.10 |
---|---|
두 테이블 조건을 설정하여 한 테이블을 업데이트하는 방법 (0) | 2023.01.10 |
Java Enum 메서드 - 반대 방향 열거를 반환합니다. (0) | 2023.01.10 |
Stripe() 값이 잘못되었습니다.apiKey는 문자열이어야 합니다.지정한: 정의되지 않음 (0) | 2023.01.10 |
Spring Security를 사용하여 Java 코드에서 "hasRole"을 확인하는 방법 (0) | 2023.01.10 |