현재 방식
import { initSentry, useMount } from '@extension/shared'
개선 후 방식
import { initSentry } from '@extension/shared/utils'
import { useMount } from '@extension/shared/hooks'
현재 방식은 @extension/shared패키지로부터 모두 import가 된다. 변수명으로 어느정도 파악은 가능하지만 훅인지, 유틸 함수인지 구분하기가 어렵다는 불편함이 있다. 이를 개선하고자 한다.
import
// pages/new-tab/src/index.tsx
import { initSentry } from '@extension/shared';
export
// packages/shared/utils/extension/initSentry.ts
export const initSentry = async (sentryDsn: string) => {
// ..
};
// packages/shared/utils/extension/index.ts
export * from './initSentry';
// packages/shared/index.ts
export * from './lib/utils/extension';
build
// packages/shared/build.mjs
const buildOptions = {
entryPoints: ['./index.ts', './lib/**/*.ts'],
// ..
};
await esbuild.build(buildOptions);
script
// packages/shared/packages.json
{
// ..
"script":{
// ..
"ready": "node build.mjs",
}
}
정리하면 다음과 같다. node build.mjs를 실행하여 빌드 스크립트가 담긴 파일을 실행한다. esbuild.build메서드를 이용하여 빌드를 진행한다. 이 때, 진입 경로는 ./index.ts, 그리고 ./lib/**/*.ts이다.
[entryPoints](https://guesung.notion.site/entryPoints-10589de02fde8068b381c1b5106aae5e)
esbuild의 entryPoints로 어떤 파일을 진입점으로 사용할지, 즉 어떤 파일을 빌드할지 지정할 수 있다.
또한, outdir옵션으로 어디 폴더에 이 빌드한 파일을 저장할지 지정할 수 있다
package.json의 exports옵션으로 어떤 경로에서 어떤 파일을 import해올 수 있을지 결정할 수 있다.
이를 이용하면 된다고 판단하였다.
// packages/shared/package.json
{
"name":"@extension/shared",
"files": [
"dist"
],
"exports": {
".": "./index.ts",
"./hooks": "./src/hooks/index.ts",
},
}
위와 같이 설정할 경우, @extension/shared/hooks는 packages/shared/dist/hooks를 검색할 것이라 생각했다.

하지만 여전히 찾을 수 없다고 뜬다.
@extension/shared에서만 찾을 수 있다고 한다.
exports
// package.json
"exports": {
".": "./src/index.ts",
"./array": "./src/array/index.ts",
"./compat": "./src/compat/index.ts",
// ..
},
files
// package.json
"files": [
"dist",
"*.d.ts"
],
src/index
// src/index.ts
export * from './array/index.ts';
export * from './error/index.ts';
export * from './function/index.ts';
// ..
array/index
// src/array/index.ts
export { at } from './at.ts';
export { chunk } from './chunk.ts';
export { compact } from './compact.ts';
export { countBy } from './countBy.ts';
// ..
사용 방법
import { at } from 'es-toolkit/array';
const numbers = [10, 20, 30, 40, 50];
const result = at(numbers, [1, 3, 4]);
console.log(result); // [20, 40, 50]