bestsource

Javascript 패키지의 하위 폴더에서 가져오기

bestsource 2023. 6. 8. 21:14
반응형

Javascript 패키지의 하위 폴더에서 가져오기

여러 폴더로 구성된 유형 스크립트 라이브러리가 있습니다.각 폴더에는 일부 비즈니스 논리를 내보내는 index.ts 파일이 포함되어 있습니다.콜 사이트에서 이 동작을 수행하기 위해 롤업과 함께 제공하려고 합니다.

import { Button, ButtonProps } from 'my-lib/button'
import { Input, Textarea } from 'my-lib/input'
import { Row, Column } from 'my-lib/grid'

다음은 디렉토리 구조입니다.

여기에 이미지 설명 입력

메인이 있습니다.index.tssrc/다음이 포함됩니다.

export * from './button';
export * from './input';
export * from './grid';

이 스타일을 사용하면 다음을 수행할 수 있습니다.

import { Button, Input, InputProps, Row, Column } from 'my-lib'

하지만 나는 이것을 원하지 않습니다.각 모듈에 네임스페이스로 액세스하고 싶습니다.에서 index.ts할 수 다음과 같습니다.

import { Button } from 'my-lib/dist/button'

전에 본 적이 없는 것입니다. 추가하기dist/Import 문으로 이동하면 상대 경로를 통해 모듈에 액세스할 수 있습니다.나는 되고 싶다.my-lib/Button.

롤업을 하고 있습니다.사용하려고 했습니다.alias플러그인이 작동하지 않았습니다.다음은 롤업 구성입니다.

const customResolver = resolve({
  extensions: ['ts'],
});

export default {
  input: `src/index.ts`,
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      sourcemap: true,
      // plugins: [terser()],
    },
    {
      file: pkg.module,
      format: 'es',
      sourcemap: true,
      plugins: [terser()],
    },
  ],
  // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
  external: [],
  watch: {
    include: 'src/**',
  },
  plugins: [
    // Allow json resolution
    json(),
    // Compile TypeScript files
    typescript({ useTsconfigDeclarationDir: true }),
    // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
    commonjs(),
    // Allow node_modules resolution, so you can use 'external' to control
    // which external modules to include in the bundle
    // https://github.com/rollup/rollup-plugin-node-resolve#usage
    resolve(),

    // Resolve source maps to the original source
    sourceMaps(),
    alias({
      entries: [
        { find: 'my-lib/button', replacement: './dist/button' },
        { find: 'my-lib/input', replacement: './dist/input' },
        { find: 'my-lib/grid', replacement: './dist/grid' },
      ],
      customResolver,
    }),
  ],
};

은 그고이것은입니다.tsconfig파일 이름:

{
  "compilerOptions": {
    "target": "es5",
    "module": "ES6",
    "lib": ["ES2017", "ES7", "ES6", "DOM"],
    "declaration": true,
    "declarationDir": "dist",
    "outDir": "dist",
    "sourceMap": true,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "allowJs": false,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "baseUrl": "./src",
    "paths": {
      "my-lib/button": ["./src/button"],
      "my-lib/input": ["./src/input"],
      "my-lib/grid": ["./src/grid"]
    }
  },
  "exclude": ["node_modules", "dist", "**/*.test.ts"],
  "include": ["src/**/*.ts"]
}

어떻게 하면 같은 구조를 이룰 수 있을지 모르겠습니다.lodash/xxx또는material-ui/yyy롤업하여

사람들이 가명이나 이름 있는 수출을 제안하지만 저는 그것을 할 수 없었습니다.

제 문제에 가장 가까운 것은 아래 질문입니다.

npm 패키지의 하위 폴더에서 가져오기

저는 같은 것을 성취하고 싶지만 그것으로.typescript그리고.rollup.

뭔가 빠진 것 같아요, 감사합니다.

이것은 가능하지만 몇 가지 추가 단계가 필요합니다.위에서 언급한 바와 같이, 이것은 Material-UI가 취하는 접근 방식입니다.

요령은 큐레이티드를 게시하는 것입니다.dist폴더, 즉 repo의 루트 폴더입니다.

건물

먼저 라이브러리가 공용을 사용하여 작성되었는지 여부는 중요하지 않습니다.JS 또는 ESM.이것은 모듈 해상도에 관한 것입니다.

프로젝트의 이름이 다음과 같다고 가정합니다.my-package.

프로젝트는 되고 있습니다.src/dist/을 가질 것입니다

my-package
  package.json
  src/
    index.js
  dist/
    index.js

포장지에 넣어주세요.제이손

"main": "dist/index.js"

또는 형식

"module": "dist/index.js"

게시

대부분의 프로젝트는 단지 추가할 뿐입니다..npmignore프로젝트의 루트를 게시하여 설치하면 프로젝트가 종료됩니다.node_modules 예:

node_modules
  my-package/
    package.json
    dist/
      index.js

해결

설치가 완료되면 다음 가져오기를 고려합니다.

import myProject from "my-project";

모듈 리졸바는 다음을 수행합니다(전체 알고리즘은 여기서는 관련이 없으므로 크게 단순화합니다).

  • 에 가다node_modules
  • » my-project
  • package.json
  • 을 일반환위에 합니다.main또는module

우리가 가지고 있기 때문에 효과가 있을 것입니다.

node_modules
  my-package/
    package.json
    dist/
      index.js

하위 경로 확인

import something from "my-project/something";

해상도 알고리즘은 다음과 같이 작동합니다.

node_modules
  my-project/
    somthing.js

또한

node_modules
  my-project/
    something/
      index.js

와 함께

node_modules
  my-project/
    something/
      package.json

후자의 경우에는 다시 살펴볼 것입니다.main또는module.

하지만 다음과 같은 이점이 있습니다.

node_modules
  my-package/
    package.json
    dist/
      index.js

트릭

유용한 것은 프로젝트 루트를 게시하는 것입니다.dist폴더, "솔직히"dist폴더 및 게시dist폴더 사용npm publish dist대신.

프랭크(프랭크 편지에서와 같이)는 당신이 작성해야 한다는 것을 의미합니다.package.json당신의dist폴더; 추가README.md LICENSE기타.

이 작업을 수행하는 방법에 대한 꽤 짧은 예를 여기에서 찾을 수 있습니다.

구축 후 다음과 같은 이점이 있습니다.

node_modules
  my-package/
    package.json
    dist/
      index.js
      something.js

일단 출판되면 우리는 얻게 됩니다.

node_modules
  my-project/
    package.json
    index.js
    something.js

어디에package.json큐레이션된 것입니다.

무엇보다도, 유일한 차이점은

import { Button } from 'my-lib/dist/button'

그리고.

import { Button } from 'my-lib/button'

디렉터리 수준이 하나 더 있을 뿐입니다.

한 번 그렇게 말하면, 당신이 할 때까지."outDir": "dist",당신의tsconfig.json추가해야 하는 파일dist/당신에게import진술들.

실제로, 당신이 예로 든 두 라이브러리는 루트 디렉터리에 있는 파일과 함께 배포됩니다: lodash는 직접적으로.js루트에 있는 파일은 material-ui에 없습니다.outDir그것의 선택권.tsconfig.jsonfile(루트 디렉토리에 출력 파일을 쓰는 것을 의미).

이게 도움이 되길 바랍니다.

수많은 시행착오 끝에 preserveModules preserveModulesRoot 옵션과 간단한 설치 후 스크립트를 사용하여 입력 목록을 전달하여 이 작업을 수행할 수 있었습니다.

여기 제 롤업.config.js가 있습니다.

const options = {
  input: [
    'src/index.ts',
    'src/api/index.ts',
    'src/components/index.ts',
    'src/contexts/index.ts',
    'src/hooks/index.ts',
    'src/lib/index.ts',
    'src/types/index.ts',
    'src/utils/index.ts',
    'src/UI/index.ts',
  ],
  output: [
    {
      format: 'cjs',
      dir: 'dist',
      exports: 'auto',
      preserveModules: true,
      preserveModulesRoot: 'src',
      sourcemap: true,
    },
  ],
  plugins: [
    // Preferably set as first plugin.
    peerDepsExternal(),
    typescript({
      tsconfig: './tsconfig.rollup.json',
    }),
    postcss({
      extract: false,
      modules: true,
      use: ['sass'],
    }),
  ],
};

export default options;

스크립트/설치 후.

#!/usr/bin/env bash
set -e;

# skip postinstall if npm install for development
# rollup.config.js is not included in dist
if [ -f "rollup.config.js" ]; then
  echo "skipping your package's postinstall routine.";
  exit 0;
fi

echo 'Copying files from dist folder into root project folder...'
cp -r dist/* ./ && rm -rf dist
echo 'Postinstall done!'

꾸러미제이손

"scripts": {
    "postinstall": "./scripts/postinstall.sh",
  },

이렇게 하면 모든 파일이 컴파일되어 dist 폴더로 출력됩니다.설치 후 스크립트는 모든 파일을 dist에서 루트 프로젝트 폴더로 복사합니다.

참고*: 로컬에서 npm install을 실행할 때는 설치 후 스크립트를 건너뛰어야 합니다.이 작업은 rollup.config.js가 있는지 확인하여 수행됩니다.

언급URL : https://stackoverflow.com/questions/62518396/importing-from-subfolders-for-a-javascript-package

반응형