首页 > 解决方案 > 使用 TypeScript 和 Less 文件创建组件库

问题描述

我正在构建一个 React UI 库,其中包含一些组件,如按钮、输入、文本区域等,我们称之为mylib。我将在许多项目中重用它,例如,在myApp. 我将使用 TypeScript,所以我必须将它编译为 ES6。它将使用.less文件进行样式设置。

我的问题是关于.less文件的。我不知道正确的方法是什么:我应该将它们编译成 inmyLib还是 in myApp?可以只使用 TypeScript 编译器,还是出于任何原因也使用 Webpack 更好?我做了一个尝试,但我不确定它是否正确。

我对此的看法是在 中编译 TypeScript myLib,但让我们myApp编译.less文件:我在文件夹中有源代码,我用 TypeScript 编译器src将它编译到一个文件夹中。dist然后在同一个脚本中,我将.less文件从复制srcdist使用cd src && find . -name '*.less' -exec rsync -R {} ../dist ';'.

这是mylib编译前的树:

.
├── README.md
├── dist // destination folder
├── package.json
├── src
│   ├── components
│   │   └── MyComponent
│   │       ├── MyComponent.less
│   │       └── MyComponent.tsx
│   ├── css
│   │   ├── constants.less
│   │   ├── imports.less
│   │   └── reset.less
│   └── index.tsx
└── tsconfig.json

这是MyComponent.tsx

import React from 'react';
import './MyComponent.less';

class MyComponent extends React.Component {
    render() {
        return <div className="MyComponent">My component</div>;
    }
}

export default MyComponent;

这是MyComponent.less

@c: .MyComponent;

@{c} {
    font-size: 20px;
    color: tomato;
}

的内容tsconfig.json是:

{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "jsx": "react",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "outDir": "dist"
  }
}

package.json 的内容是:

{
  "name": "@me/mycomponents",
  "version": "0.0.0",
  "description": "Components library",
  "scripts": {
    "build": "tsc -d && cd src && find .  -name '*.less' -exec rsync -R {} ../dist ';' && cd .."
  },
  "devDependencies": {
    "typescript": "^3.6.2",
    "react-dom": "^16.9.0"
  },
  "dependencies": {
    "prop-types": "^15.7.2",
    "react": "^16.9.0",
  }
}

编译后我得到这个:

.
├── README.md
├── dist
│   ├── components
│   │   └── MyComponent
│   │       ├── MyComponent.d.ts
│   │       ├── MyComponent.js
│   │       └── MyComponent.less
│   ├── css
│   │   ├── constants.less
│   │   ├── imports.less
│   │   └── reset.less
│   ├── index.d.ts
│   └── index.js
├── package.json
├── src
│   ├── components
│   │   └── MyComponent
│   │       ├── MyComponent.less
│   │       └── MyComponent.tsx
│   ├── css
│   │   ├── constants.less
│   │   ├── imports.less
│   │   └── reset.less
│   └── index.tsx
└── tsconfig.json

然后从myApp我应该能够导入MyComponent并让myApp编译less文件。

这种方法听起来对你吗?

标签: javascripttypescriptnpmwebpackbundle

解决方案


[更少的文件:] 我应该在 myLib 中还是在 myApp 中编译它们?

  • 你的组件库应该提供.less源代码和.css输出

  • .css对非少消费者有好处,因此他们仍然可以利用您的风格

  • .less适合那些可能使用不太具体的功能(如 mixins 或其他)的消费者

可以只使用 TypeScript 编译器,还是出于任何原因也使用 Webpack 更好?

  • 是的,理想情况下,您的组件库应该只使用 typescript 编译器来生成dist/**/*.js文件

  • 将捆绑、缩小、优化、polyfilling 和这些类型的问题留给消费应用程序

  • 您还应该配置您以与 javascript 输出并排tsconfig.json生成声明文件(以便打字稿消费者可以从打字/代码提示/自动完成中受益).d.ts

    • 添加"declaration": true到您的`tsconfig.json
    • 您可能还想添加源映射以进行调试"sourceMap": true

推荐阅读