首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建React组件库

创建React组件库
EN

Stack Overflow用户
提问于 2019-03-05 13:44:45
回答 3查看 3K关注 0票数 1

我正在用React和TypeScript用Babel 7创建一个模块化组件库。

我希望我的库的用户使用类似如下的语法导入组件:

代码语言:javascript
复制
import SomeComponent from "my-awesome-lib/SomeComponent"

SomeComponent是我的-awesome lib包中的一个TSX模块:

代码语言:javascript
复制
import * as React from "react";

export default function () {
  return <h1>SomeComponent</h1>
}

my- And component的package.json文件的main字段为:

代码语言:javascript
复制
"main": "src/index.ts"

我不想发布我的组件库的编译版本,因为我在我的组件中导入了CSS和其他资产,我希望我的包的所有用户都使用带有一些特定配置的Webpack。

现在我的问题是,从“my -awesome/ SomeComponent”导入SomeComponent失败,并出现解析错误:

代码语言:javascript
复制
ERROR in ../node_modules/wtf/index.tsx 4:9
Module parse failed: Unexpected token (4:9)
You may need an appropriate loader to handle this file type.
| 
| export default function () {
>   return <h1>WTF</h1>
| }

看来,在node_modules中,Webpack并没有加载或转换TSX文件。

我在我的用户应用程序的根目录下使用了这个tsconifg.json (它导入了my - at lib):

代码语言:javascript
复制
{
  "compilerOptions": {
    "outDir": "./dist",
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "downlevelIteration": true,
    "lib": ["es5", "es2015", "dom", "scripthost"], 
    "typeRoots": ["node_modules/@types", "src/@types"],
  },
  "include": ["src/**/*", "node_modules/**/*"],
  "exclude": []
}

而Webpack的相关配置如下:

代码语言:javascript
复制
const tsModules = {
  test: /\.(js|jsx|ts|tsx)$/,
  include: [path.resolve('src')],
  exclude: /node_modules/,
  loader: 'babel-loader'
}

const resolve = {
  alias: {
  },
  modules: [
    'node_modules'
  ],
  extensions: ['.tsx', '.ts', '.js']
}

module.exports = {
   ...
   context: resolve('src'),
   resolve: resolve,
   module: {
     rules: [
       tsModules,
       ...
     ]
   }
}

如何让Webpack从node_modules加载和转换我的-awesome lib的TSX模块?

EN

回答 3

Stack Overflow用户

发布于 2019-03-05 14:09:51

此设置假设您正在使用样式组件,并且没有css/scss。

这里重要的是在你的tsconfig中有"module":commonJS,在你的webpack配置中有libraryTarget:"commonJS“。External告诉webpack不要将你的库与React、React-DOM或styled-components捆绑在一起,而是在你要导入到的项目中寻找那些包。

您还需要将React、react-dom和styled components从package.json依赖项中取出,并将这些包放入您的对等依赖项中

代码语言:javascript
复制
   const path = require("path");
    const fs = require("fs");
    const TerserPlugin = require('terser-webpack-plugin');
    const appIndex = path.join(__dirname, "../src/main.tsx");
    const appBuild = path.join(__dirname, "../storybook-static");
    const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

    module.exports = {
        context: fs.realpathSync(process.cwd()),
        mode: "production",
        bail: true,
        devtool: false,
        entry: appIndex,
        output: {
            path: appBuild,
            filename: "dist/Components.bundle.js",
            publicPath: "/",
            libraryTarget: "commonjs"
        },
        externals: {
            react: {
                root: 'React',
                commonjs2: 'react',
                commonjs: 'react',
                amd: 'react'
            },
            'react-dom': {
                root: 'ReactDOM',
                commonjs2: 'react-dom',
                commonjs: 'react-dom',
                amd: 'react-dom'
            },
            "styled-components": {
                root: "styled-components",
                commonjs2: "styled-components",
                commonjs: "styled-components",
                amd: "styled-components"
            }
        },
        optimization: {
            minimizer: [
                new TerserPlugin({
                    terserOptions: {
                        parse: {
                            ecma: 8,
                        },
                        compress: {
                            ecma: 5,
                            warnings: false,
                            comparisons: false,
                            inline: 2,
                        },
                        mangle: {
                            safari10: true,
                        },
                        output: {
                            ecma: 5,
                            comments: false,
                            ascii_only: true,
                        },
                    },
                    parallel: true,
                    cache: true,
                    sourceMap: false,
                })
            ],
        },
        resolve: {
            extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx", ".ts", ".tsx"],
            alias: {
                "react-native": "react-native-web",
            },
        },
        module: {
            strictExportPresence: true,
            rules: [
                { parser: { requireEnsure: false } },
                {
                    test: /\.(ts|tsx)$/,
                    loader: require.resolve("tslint-loader"),
                    enforce: "pre",
                },
                {
                    oneOf: [
                        {
                            test: /\.(tsx?)$/,
                            loader: require.resolve('awesome-typescript-loader'),
                            options: {
                                configFileName: 'tsconfig.prod.json'
                            }
                        },
                    ],
                },
            ],
        },
        plugins: [
            new TsConfigPathsPlugin()
        ],
        node: {
            dgram: "empty",
            fs: "empty",
            net: "empty",
            tls: "empty",
            child_process: "empty",
        },
        performance: false,
    };

注意:将应用程序中的一个点作为只包含您想要导出的组件的条目,这一点很重要。

也就是说,对于我来说,它是Main.tsx,在Main.tsx内部,它看起来是这样的。

代码语言:javascript
复制
export { Checkbox } from "./components/Checkbox/Checkbox";
export { ColorUtils } from "./utils/color/color";
export { DataTable } from "./components/DataTable/DataTable";
export { DatePicker } from "./components/DateTimePicker/DatePicker/DatePicker";
export { DateTimePicker } from "./components/DateTimePicker/DateTimePicker/DateTimePicker";
export { Disclosure } from "./components/Disclosure/Disclosure";

这意味着webpack不会捆绑你不打算出口的东西。要测试您的捆绑包works,请尝试从捆绑包中导入一些带有require语法的内容,以绕过typescript类型,并在tsconfig中将allowJS设置为true。

类似const Button =require(“../path/to/js/console.log”).Button console.log(按钮);

票数 1
EN

Stack Overflow用户

发布于 2019-03-05 16:12:29

我发现create-react-library非常有用

票数 1
EN

Stack Overflow用户

发布于 2019-03-05 16:30:09

您正在排除node_modules目录(这通常是件好事):

代码语言:javascript
复制
const tsModules = {
  test: /\.(js|jsx|ts|tsx)$/,
  include: [path.resolve('src')],
  exclude: /node_modules/,
  loader: 'babel-loader'
}

除了明确排除node_modules文件夹之外,由于src中的include属性,您还只允许babel-loader处理tsModules文件夹的内容。所以这个错误:

../node_modules/wtf/index.tsx 4:9模块解析失败:意外标记(4:9)中的

错误

合乎道理。

如果删除node_modules属性并在tsModules.exclude中更改正则表达式,则仍可以排除tsModules.include,但单个文件夹除外

代码语言:javascript
复制
const tsModules = {
  // ...
  exclude: /node_modules\/(?!my-awesome-lib)\/*/
  // ...
}

也可以,但是我还没有测试它,将my-awesome-lib目录添加到include数组中:

代码语言:javascript
复制
const tsModules = {
  // ...
  include: [
    path.resolve(__dirname, './src'),
    path.resolve(__dirname, './node-modules/my-awesome-lib')
  ]
  // ...
}

然后,您的node_modules/my-awesome-lib目录中的文件将传递babel-loader,它将转换typescript代码。

编辑:我想你的混淆来自于你的tsconfig.json文件和"include": ["src/**/*", "node_modules/**/*"],。巴别塔是在转译你的代码,而不是打字。因此,在根目录中放置一个tsconfig.json文件可能会对您的集成开发环境有所帮助(特别是如果您使用的是微软的VScode),但不会影响babel@babel/preset-typescript如何转换您的代码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54996147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档