React

[react] Dynamic Import (lazy) 의 Rule

우주유령 2023. 2. 2. 09:10
728x90
반응형

vite-react환경에서 dynamic import를 하려고 했는데 아래와 같은 오류가 났다.

내가 짠 코드는 이렇다.

import {lazy, Suspense} from 'react';
import LoadingComponent from '@/components/Loading/LoadingComponent.jsx';

const ViewContainer = ({ path }) => {
    const View = lazy(() => import(path));

    return (
        <>
            <Suspense fallback={LoadingComponent}>
                <View />
            </Suspense>
        </>
    );
};

export default ViewContainer;

path가 맞는데도, import되지 않는 오류가 났다. 찾아보니 dynamic import시 아래와 같은 룰이 있다.

 

 

Dynamic Import Rule

Rollup에 나와 있는 내용이다.

https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations

 

GitHub - rollup/plugins: 🍣 The one-stop shop for official Rollup plugins

🍣 The one-stop shop for official Rollup plugins. Contribute to rollup/plugins development by creating an account on GitHub.

github.com

 

bundling할 때 static analysis( 정적 분석 )이 가능해야 한다.

아래와 같이 변수만 넣을 경우 이론적으로, 모든 파일 시스템을 import할 수 있다.

function importModule(path) {
  // who knows what will be imported here?
  return import(path);
}

좋지 않은(이상한?) 케이스를 방지하기 위해 몇 가지 룰을 정했다.

 

 

Imports must start with ./ or ../.

모든 import는 상대경로로 시작해야 한다. 변수, 절대경로, bare import 이면 안된다.

// Not allowed
import(bar);
import(`${bar}.js`);
import(`/foo/${bar}.js`);
import(`some-library/${bar}.js`); //bare import

 

 

Imports must end with a file extension

의도치 않은 파일이 import 될 수 있기 때문에 확장자로 끝나야 한다.

// Not allowed
import(`./foo/${bar}`);
// allowed
import(`./foo/${bar}.js`);

 

 

Imports to your own directory must specify a filename pattern

파일 명칭에 패턴이 있다면, 의도치 않은 import 방지를 위해 패턴을 포함시켜라

// not allowed
import(`./${foo}.js`);
// allowed
import(`./module-${foo}.js`);

 

 

Globs only go one level deep

glob를 사용할 때, 하나의 변수는 하나의 depth당 최대 * 로 치환된다. 이것은 의도치 않게 너무 많은 파일 디렉토리를 import하지 않도록 해준다.

아래는 ./foo/**/*.js 이 아니고, ./foo/*/*.js 이다.

import(`./foo/${x}${y}/${z}.js`);
728x90
반응형