Как стать автором
Обновить

Создание npm пакета React компонентов на базе create-react-app

Время на прочтение3 мин
Количество просмотров16K

В данной публикации мы рассмотрим, как создать npm пакет React компонентов используя create-react-app.


Инициализация проекта


create-react-app create-react-app-npm
cd create-react-app-npm
yarn run eject
yarn add -D babel-preset-es2015 babel-preset-stage-0 babel-preset-react

Создать .babelrc


{
  "presets": ["es2015", "react", "stage-0"]
}

Изменить package.json


...
  "name": "create-react-app-npm",
  "version": "0.0.1",
  "main": "lib/index.js",
  "dependencies": {
...
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "lib": "babel src/node_modules --out-dir lib --copy-files",
    "test": "node scripts/test.js --env=jsdom"
  },
...

Для "приемлемой" загрузки CSS


Изменить config/webpack.config.dev.js


...
      {
        test: /\.css$/,
        loader: `style!css?importLoaders=1&modules&localIdentName=[name]__[local]___[hash:base64:5]!postcss`
      },
...

Изменить config/webpack.config.prod.js


...
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(
          'style',
          'css?importLoaders=1&modules&localIdentName=[name]__[local]___[hash:base64:5]!postcss',
          extractTextPluginOptions
        )
      },
...

Создать следующую структуру папок:


src/node_modules/
src/node_modules/components/
src/node_modules/components/YourComponent/
src/node_modules/components/YourComponent1/
src/node_modules/components/YourComponent2/
...
src/node_modules/components/YourComponentN/

В каждой папке YourComponent


Создать package.json


{
  "private": true,
  "name": "YourComponent",
  "main": "./YourComponent.js"
}

Создать YourComponent.css (например)


.root {
  background: linear-gradient(to top,#fed835 20px,#ffeb3c 20px);
  font-size: 30px;
  color: white;
  line-height: 35px;
  text-align: center;
}

Создать YourComponent.js


import React                from 'react'

import s                    from './YourComponent.css'

class YourComponent extends React.Component {
  render() {
    return (
      <div className={ s.root }>
        { this.props.children }
      </div>
    )
  }
}

export default YourComponent

Создать src/node_modules/index.js


export { default as YourComponent } from './components/YourComponent'

Для демонстрации работы библиотеки изменить src/App.js


import React                from 'react'

import YourComponent        from 'components/YourComponent'

class App extends React.Component {
  render() {
    return (
      <YourComponent>
        1
      </YourComponent>
    )
  }
}

export default App

Теперь выполнив yarn run start вы можете увидеть, что получилось


Добавьте необходимые пути в .gitignore (например)


/node_modules
/coverage
/build

.DS_Store
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*
yarn.lock

.idea

Скомпилируйте библиотеку


yarn run lib

Создайте репозиторий на github


Привяжите проект к созданному репозиторию


git init
git remote add origin https://github.com/lokhmakov/create-react-app-npm.git

Добавьте файлы, сделайте commit и опубликуйте результат


git add .
git commit -m "init"
git push -u origin master
npm publish

Вы закончили. Теперь можно использовать вашу библиотеку следующим образом


yarn add create-react-app-npm

import { YourComponent } from 'create-react-app-npm'

Create-react-app-npm
Best way to create npm packages with create-react-app

Теги:
Хабы:
Всего голосов 10: ↑9 и ↓1+8
Комментарии14

Публикации

Истории

Работа

Ближайшие события