繁体   English   中英

从 javascript package 的子文件夹导入

[英]Importing from subfolders for a javascript package

我有一个 typescript 库由多个文件夹组成。 每个文件夹都包含一个 index.ts 文件,该文件导出一些业务逻辑。 我正在尝试将此与汇总捆绑在一起以在呼叫站点上实现此行为:

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

这是目录结构:

在此处输入图像描述

我在src/下有一个主index.ts ,其中包含:

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"]
}

我不知道如何通过 rollup 实现与lodash/xxxmaterial-ui/yyy相同的结构。

人们建议使用别名或命名导出,但我无法使其工作。

最接近我的问题的是以下问题:

从 npm package 的子文件夹导入

我想实现同样的事情,但使用typescriptrollup

我想我错过了一些东西,谢谢。

首先,两者之间的唯一区别

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

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

只是一个目录级别。

曾经说过,直到你有"outDir": "dist",在你的tsconfig.json文件中,你需要将dist/添加到你的import语句中。

确实,您作为示例的两个库都与根目录中的文件一起分发: lodash直接在根目录中有js文件,而material-ui在其tsconfig.json文件中没有outDir选项(这意味着将Z78E62261F6389F1CED668文件写入根目录) .

希望这可以帮助。

这是可能的,但需要一些额外的步骤。 上面提到过,这是Material-UI采用的方法。

诀窍是发布一个精选的dist文件夹,而不是你的 repo 的根文件夹。

建造

首先,让我们明确一点,您的库是使用 CommonJS 还是 ESM 构建的并不重要。 这是关于模块分辨率的。

假设该项目名为my-package

现在大多数项目,在我们将src/构建到dist/之后,

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

并在 package.json

"main": "dist/index.js"

或对于 esm

"module": "dist/index.js"

出版

大多数项目只是添加.npmignore并发布项目的根目录,因此在安装时,项目最终会出现在node_modules中,如下所示:

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

正在解决

安装后,考虑这个导入:

import myProject from "my-project";

模块解析器将执行此操作(大大简化,因为完整的算法在这里无关紧要):

  • Go 到node_modules
  • 查找my-project
  • 加载package.json
  • 返回mainmodule中的文件

这会起作用,因为我们有

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

在后一种情况下,它将再次查看mainmodule

但我们有:

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

诀窍

诀窍是,不要使用dist文件夹发布项目根目录,而是“坦白” dist文件夹并使用npm publish dist dist夹来发布 dist 文件夹。

坦率地说(如坦率的一封信),您需要在dist文件夹中创建一个package.json 添加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是策划的。

经过多次试验和错误后,我能够通过传入输入列表、使用preserveModulespreserveModulesRoot选项以及简单的安装后脚本来完成这项工作。

这是我的rollup.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;

脚本/postinstall.sh

#!/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!'

package.json

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

这会将 output 所有文件编译到dist文件夹。 postinstall 脚本会将所有文件从dist复制到根项目文件夹中。

注意*:在本地运行 npm 安装时应跳过安装后脚本。 这是通过检查rollup.config.js是否存在来完成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM