[import-visualizer] 8. tsc의 한계 및 배포

HBSPS·2024년 6월 14일
0

import-visualizer

목록 보기
8/10

tsc를 활용하려 했지만 tsc의 한계를 만났다.

이 시리즈의 글은 개발 과정을 작성한 것으로 내용 중 코드 또는 판단이 이상한 부분이 있다면 높은 확률로 뒷부분에서 수정될 것입니다.

tsc의 한계

#!/usr/bin/env node
import open from 'open';
import { resolve } from 'path';
import { unlink } from 'fs/promises';
import { cliConfig } from '../plugin/cliConfig';
import { getConfigFile } from '../plugin/getConfigFile';
import { FileTree } from '../plugin/FileTree';
import { generateTemplate } from '../plugin/generateTemplate';
async function cli(config = process.argv.slice(2)) {
    const { root, targetDir } = cliConfig(config);
    const { compilerOptions } = getConfigFile();
    const { baseUrl, paths } = compilerOptions;
    const fileTree = new FileTree(root, targetDir, baseUrl, paths);
    generateTemplate(fileTree.tree);
    const resultFilePath = resolve(process.argv[1], '../../index.html');
    await open(resultFilePath, { wait: true });
    console.log('Tree has been created. Check your browser.');
    await unlink(resultFilePath);
}
export default cli;

tsc를 활용한 결과는 위와 같다.

여기서 중요한 점은 import에서 확장자가 없다는 것이다.

이렇게 되었을 때 문제점은 라이브러리를 사용하는 프로젝트에서 저 파일들의 경로를 알 수 없기 때문에 파일을 찾을 수 없다는 오류가 발생하는 것이다.

typescript의 issue를 확인해보면 타입스크립트의 철학에 따라 확장자를 추가하는 변환은 자동으로 이루어지지 않는다는 것을 알 수 있다.

단순히 JS를 TS로 트랜스파일링 하는 것이 목표이며 이에 대해 추가적인 작업을 통해 코드를 수정하는 행위를 지양한다는 것이 핵심 주장이다.

https://github.com/microsoft/TypeScript/issues/40878

최근까지 문제가 제기되고 있지만 해결될 기미는 보이지 않았다.

rollup

이미 프로젝트에서 rollup을 사용하기로 했으니 이를 활용하기로 했다.

import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';

export default [
  {
    input: './bin/cli.ts',
    output: {
      format: 'es',
      dir: 'dist',
      preserveModules: true,
    },
    external: ['open', 'json5', '@babel/parser', '@babel/traverse', 'fs', 'path', 'fs/promises'],
    plugins: [
      typescript({
        tsconfig: 'tsconfig.json',
      }),
      json(),
    ],
  },
];

리액트 빌드와 별개로 rollup.config.js 파일을 하나 생성하고 이를 활용하도록 한다.

이것을 토대로 빌드를 수행해보면 아래와 같은 결과를 얻을 수 있다.

#!/usr/bin/env node
import open from 'open';
import { resolve } from 'path';
import { unlink } from 'fs/promises';
import { cliConfig } from '../plugin/cliConfig.js';
import { getConfigFile } from '../plugin/getConfigFile.js';
import { FileTree } from '../plugin/FileTree.js';
import { generateTemplate } from '../plugin/generateTemplate.js';

const { root, targetDir } = cliConfig(process.argv.slice(2));
const { compilerOptions } = getConfigFile();
const { baseUrl, paths } = compilerOptions;
const fileTree = new FileTree(root, targetDir, baseUrl, paths);
generateTemplate(fileTree.tree);
const resultFilePath = resolve(process.argv[1], '../../index.html');
await open(resultFilePath, { wait: true });
console.log('Tree has been created. Check your browser.');
await unlink(resultFilePath);

rollup을 활용하여 확장자가 잘 붙어있고 이를 바탕으로 실제 파일들에 접근하는데 문제가 없음을 알 수 있다.

link된 프로젝트에서 다시 한 번 실행해보면 다시 결과가 잘 나오는 것을 알 수 있다.

압축

파일의 결과가 압축되지 않았다는 것을 알 수 있다.

압축, 난독화 등을 수행하지 않고 이대로 둔 이유는 우선 번들 크기가 그렇게 크지 않기 때문이다.
(다른 라이브러리들 중 그대로 두는 라이브러리도 많았다)

또한, 브라우저에서 실시간으로 요청을 보내거나 하지 않고 한 번 설치해서 그냥 사용하는 경우가 많을 것이기 때문에 디버깅용을 위해서라도 그대로 남겨두기로 했다.

배포

(package.json의 내용은 생략)

배포를 위해 package.json에 라이브러리 관련 내용들을 넣어주고 아래와 같은 순서로 배포할 수 있었다.

npm info <패키지 이름>

확인 결과 해당 이름을 갖는 라이브러리는 존재하지 않는다는 것을 알 수 있다.

npm publish

배포 명령어를 입력하고 다시 한 번 정보를 확인해보면 아래와 같다.

이제는 라이브러리가 잘 배포되었음을 알 수 있다.

import-visualizer - npm (npmjs.com)

다른 프로젝트에서 이 라이브러리를 설치할 수 있으며 사용할 수 있는 것을 확인한다.

profile
대체로 맑음

0개의 댓글

관련 채용 정보