0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

初期化 ゼロからReact コンポーネントライブラリ(1)

Last updated at Posted at 2023-12-13

最近、自分のReactコンポーネントライブラリを作ってみたいと思います。
千里の旅も一歩から、始めましょう。

storybook プロジェクト 初期化

npm
npm init

アップロード

git
git init
git commit -m "first commit"
git branch -M master
git remote add origin git@github.com:***/***.git
git push -u origin master

.gitignore

cmd-cli
echo // project> .gitignore
echo node_modules> .gitignore
echo;>> .gitignore
echo // vscode>> .gitignore
echo .history>> .gitignore

webpack

npm
npm install webpack webpack-cli --save-dev
npm
npm i typescript ts-loader --save-dev
npx tsc --init
npx storybook@latest init

storybook スタイルの配置 storybook:theme
image.png

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

storybook loader
1.ローダーを追加する

npm
npm install --save-dev css-loader sass-loader

2.配置を追加する
image.png

./storybook/main.ts
./storybook/main.ts
import type { StorybookConfig } from "@storybook/react-webpack5";
import { Configuration } from "webpack";

const config: StorybookConfig = {
  stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-onboarding",
    "@storybook/addon-interactions",
  ],
  framework: {
    name: "@storybook/react-webpack5",
    options: {
      builder: {
        useSWC: true,
      },
    },
  },
  docs: {
    autodocs: "tag",
  },
  webpackFinal: async (config: Configuration) => {
    const { module = {} } = config;
    const { rules = [] } = module;
    return {
      ...config,
      module: {
        ...module, rules: [
          ...rules,
          {
            test: /\.sass$/,
            use: [
              { loader: 'style-loader' },
              {
                loader: 'css-loader',
                options: {
                  modules: true,
                },
              },
              { loader: 'sass-loader' },
            ],
          },
        ]
      },
    };
  },
};
export default config;

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Cannot find module 'sass'

npm
npm install --save-dev sass

成功して実行する
image.png

ログインchromatic プロジェクトtokenを作成する
npx chromatic --project-token=token

Cannot find module './Button.sass' or its corresponding type declarations.ts(2307)

global.d.ts
declare module '*.sass' {
    const content: Record<string, string>;
    export default content;
}

No inputs were found in config file 'd:/coding/choas-react/tsconfig.json'. Specified 'include' paths were '[]' and 'exclude' paths were '["node_modules"]'.ts

tsconfig.json
"include": [
    "./src/**/*"
]

コンポーネント プロジェクト 初期化

init
npm init
npx tsc init
git init
npm i --save-dev webpack webpack-cli react-dom react sass typescript
npm i --save-dev css-loader style-loader ts-loader sass-loader
npm i --save-dev fs path

image.png

build.js
const { exec } = require('child_process');
const path = require('path');

exec('npx webpack --config ' + path.resolve(__dirname, './webpack/common.js'), console.log);
webpack/common.js
const path = require('path');
const TerserWebpack =  require("terser-webpack-plugin");
const { createEntries } = require('./function');

module.exports = {
    entry: createEntries(),
    mode: "production",
    output: {
        path: path.join(__dirname, '../../lib'),
        filename: '[name].js',
    },
    module: {
        rules: [
            {
                test: /\.sass$/,
                use: [
                    { loader: 'style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                        },
                    },
                    { loader: 'sass-loader' },
                ],
            },
            {
                test: /\.tsx?$/,
                use: [
                    { loader: 'ts-loader' },
                ]
            }
        ]
    },
    plugins:[
        new TerserWebpack({
            extractComments: false,
        })
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
};
webpack/function.js
const path = require('path');

const createEntries = () => {
    const jsonConfig = require('../component/list.json');
    let entries = {};
    Object.keys(jsonConfig).forEach(key => {
        entries[key] = './src/' + jsonConfig[key];
    })
    return entries;
}

module.exports = {
    createEntries
}
init
npm run build
npm whoami
npm publish

LICENSE ファイルがremove
image.png
image.png


新しいtest-projectを作成する

App.tsx
import React from 'react';
import {Button}  from '../../choas-react/src/Button'

function App() {
  return (
    <Button>123</Button>
  );
}

export default App;

You can either move it inside src/, or add a symlink to it from project's node_modules/

stackoverflow - imports-restriction-outside-of-src-directory

package.json
"dependencies": {
  "app-b-dashboard": "file:./packages/app-b-dashboard"
}
npm
npm i 

Module parse failed: The keyword 'interface' is reserved (7:0)
File was processed with these loaders:

  • ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
  • ./node_modules/source-map-loader/dist/cjs.js
    You may need an additional loader to handle the result of these loaders.
    | import styles from './index.sass';
    |

interface ButtonProps {
| children: React.ReactNode,
| type?: 'primary' | 'danger' | 'normal' | 'dot' | 'link',

node_modulesの方法でインポートして、コンパイルされていないとおもいます。
そして、includeファイルを削除する。

image.png

実装できる。

image.png

良さはコンポネント プロジェクトの変化に伴い変化する
image.png

image.png

今三つのプロジェクトがあります。
react-component
react-storybook
react-test

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?