Commit 9d60e1ec authored by René Jochum's avatar René Jochum

Initial commit

Signed-off-by: René Jochum's avatarRené Jochum <rene@jochums.at>
parents
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
module.exports = {
extends: 'react-app',
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
settings: {
react: {
version: '16.8'
},
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx']
},
'import/resolver': {
// use <root>/tsconfig.json
typescript: {}
}
},
rules: {
'jsx-a11y/href-no-hash': 'off',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{
vars: 'all',
args: 'after-used',
ignoreRestSiblings: true,
argsIgnorePattern: '^_' // ignore unused variables whose name is '_'
}
]
}
}
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
node_modules
# builds
build
dist
lib
es
types
.rpt2_cache
# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
coverage
\ No newline at end of file
registry = "https://registry.npmjs.com/"
language: node_js
node_js:
- '11'
- '10'
- '8'
- '6'
Copyright (c) 2017 [these people](https://github.com/rollup/rollup-starter-lib/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# rollup-starter-lib
[![Greenkeeper badge](https://badges.greenkeeper.io/rollup/rollup-starter-lib.svg)](https://greenkeeper.io/)
This repo contains a bare-bones example of how to create a library using Rollup, including importing a module from `node_modules` and converting it from CommonJS.
We're creating a library called `how-long-till-lunch`, which usefully tells us how long we have to wait until lunch, using the [ms](https://github.com/zeit/ms) package:
```js
console.log('it will be lunchtime in ' + howLongTillLunch());
```
## Getting started
Clone this repository and install its dependencies:
```bash
git clone https://github.com/rollup/rollup-starter-lib
cd rollup-starter-lib
npm install
```
`npm run build` builds the library to `dist`, generating three files:
* `dist/how-long-till-lunch.cjs.js`
A CommonJS bundle, suitable for use in Node.js, that `require`s the external dependency. This corresponds to the `"main"` field in package.json
* `dist/how-long-till-lunch.esm.js`
an ES module bundle, suitable for use in other people's libraries and applications, that `import`s the external dependency. This corresponds to the `"module"` field in package.json
* `dist/how-long-till-lunch.umd.js`
a UMD build, suitable for use in any environment (including the browser, as a `<script>` tag), that includes the external dependency. This corresponds to the `"browser"` field in package.json
`npm run dev` builds the library, then keeps rebuilding it whenever the source files change using [rollup-watch](https://github.com/rollup/rollup-watch).
`npm test` builds the library, then tests it.
## Variations
* [babel](https://github.com/rollup/rollup-starter-lib/tree/babel) — illustrates writing the source code in ES2015 and transpiling it for older environments with [Babel](https://babeljs.io/)
* [buble](https://github.com/rollup/rollup-starter-lib/tree/buble) — similar, but using [Bublé](https://buble.surge.sh/) which is a faster alternative with less configuration
* [TypeScript](https://github.com/rollup/rollup-starter-lib/tree/typescript) — uses [TypeScript](https://www.typescriptlang.org/) for type-safe code and transpiling
## License
[MIT](LICENSE).
{
"name": "@minadmin/react-module",
"version": "0.0.1-dev0",
"main": "lib/react-module.js",
"unpkg": "dist/react-module.js",
"module": "es/react-module.js",
"types": "types/index.d.ts",
"files": [
"dist",
"lib",
"es",
"src",
"types"
],
"peerDependencies": {
"react": "*",
"redux": "*"
},
"dependencies": {
"@babel/runtime": "^7.8.0",
"hoist-non-react-statics": "^3.3.1",
"reflect-metadata": "^0.1.13"
},
"devDependencies": {
"@babel/core": "^7.8.0",
"@babel/plugin-transform-runtime": "^7.8.0",
"@rollup/plugin-commonjs": "^11.0.1",
"@rollup/plugin-node-resolve": "^7.0.0",
"@rollup/plugin-replace": "^2.3.0",
"@rollup/plugin-typescript": "^2.1.0",
"@types/hoist-non-react-statics": "^3.3.1",
"@types/react": "^16.9.17",
"@typescript-eslint/eslint-plugin": "^2.15.0",
"@typescript-eslint/parser": "^2.15.0",
"babel-eslint": "^10.0.3",
"eslint": "^6.8.0",
"eslint-config-react-app": "^5.1.0",
"eslint-import-resolver-typescript": "^2.0.0",
"eslint-plugin-flowtype": "^4.6.0",
"eslint-plugin-import": "^2.20.0",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.17.0",
"eslint-plugin-react-hooks": "^2.3.0",
"react": "^16.12.0",
"redux": "^4.0.5",
"rollup": "^1.29.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-terser": "^5.2.0",
"rollup-plugin-typescript2": "^0.25.3",
"ts-node": "^8.6.1",
"tslib": "^1.10.0",
"typescript": "^3.7.4"
},
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"test": "ts-node test/test.ts",
"pretest": "npm run build"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
import nodeResolve from '@rollup/plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import replace from '@rollup/plugin-replace'
import typescript from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
import commonjs from '@rollup/plugin-commonjs';
import pkg from './package.json'
const extensions = ['.ts']
const noDeclarationFiles = { compilerOptions: { declaration: false } }
const babelRuntimeVersion = pkg.dependencies['@babel/runtime'].replace(
/^[^0-9]*/,
''
)
const makeExternalPredicate = externalArr => {
if (externalArr.length === 0) {
return () => false
}
const pattern = new RegExp(`^(${externalArr.join('|')})($|/)`)
return id => pattern.test(id)
}
export default [
// CommonJS
{
input: 'src/index.ts',
output: { file: 'lib/react-module.js', format: 'cjs', indent: false, name: 'ReactModule', exports: 'named' },
external: makeExternalPredicate([
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {})
]),
plugins: [
nodeResolve({
extensions
}),
typescript({ useTsconfigDeclarationDir: true }),
babel({
extensions,
plugins: [
['@babel/plugin-transform-runtime', { version: babelRuntimeVersion }]
],
runtimeHelpers: true
}),
commonjs()
]
},
// ES
{
input: 'src/index.ts',
output: { file: 'es/react-module.js', format: 'es', indent: false },
external: makeExternalPredicate([
...Object.keys(pkg.peerDependencies || {})
]),
plugins: [
nodeResolve({
extensions
}),
typescript({ tsconfigOverride: noDeclarationFiles }),
babel({
extensions,
plugins: [
[
'@babel/plugin-transform-runtime',
{ version: babelRuntimeVersion, useESModules: true }
]
],
runtimeHelpers: true
}),
commonjs()
]
},
// ES for Browsers
{
input: 'src/index.ts',
output: { file: 'es/react-module.mjs', format: 'es', indent: false },
external: makeExternalPredicate([
...Object.keys(pkg.peerDependencies || {})
]),
plugins: [
nodeResolve({
extensions
}),
replace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
typescript({ tsconfigOverride: noDeclarationFiles }),
babel({
extensions,
exclude: 'node_modules/**'
}),
terser({
compress: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
warnings: false
}
}),
commonjs()
]
},
// UMD Development
{
input: 'src/index.ts',
output: {
file: 'dist/react-module.js',
format: 'umd',
name: 'ReactModule',
indent: false,
exports: 'named',
globals: {
'react': 'React'
}
},
external: makeExternalPredicate([
...Object.keys(pkg.peerDependencies || {})
]),
plugins: [
nodeResolve({
extensions
}),
typescript({ tsconfigOverride: noDeclarationFiles }),
babel({
extensions,
exclude: 'node_modules/**'
}),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
commonjs()
]
},
// UMD Production
{
input: 'src/index.ts',
output: {
file: 'dist/react-module.min.js',
format: 'umd',
name: 'ReactModule',
indent: false,
exports: 'named',
globals: {
'react': 'React'
}
},
external: makeExternalPredicate([
...Object.keys(pkg.peerDependencies || {})
]),
plugins: [
nodeResolve({
extensions
}),
typescript({ tsconfigOverride: noDeclarationFiles }),
babel({
extensions,
exclude: 'node_modules/**'
}),
replace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
terser({
compress: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
warnings: false
}
}),
commonjs()
]
}
]
import { getInstance } from "./inject";
import { isFunction, Token, Definition, isToken } from "./types";
import { logError, logIncorrectBinding, getDebugName } from "./errors";
import { addBinding } from './registry';
/**
* Bind type to specified class.
*/
export function toClass(constructor: new (...args: any) => any) {
if (process.env.NODE_ENV !== 'production') {
if (!isFunction(constructor)) {
logError(`Class ${getDebugName(constructor)} is not a valid dependency`);
}
}
return asBinding(() => {
const instance = new constructor();
return instance;
});
}
/**
* Bind type to specified factory function.
*/
export function toFactory(depsOrFactory: Function[] | Function, factory: Function | undefined) {
if (process.env.NODE_ENV !== 'production') {
if (factory) {
if (!Array.isArray(depsOrFactory)) {
logError(`Dependency array ${getDebugName(depsOrFactory)} is invalid`);
}
if (!isFunction(factory)) {
logError(`Factory ${getDebugName(factory)} is not a valid dependency`);
}
} else if (!isFunction(depsOrFactory)) {
logError(
`Factory ${getDebugName(depsOrFactory)} is not a valid dependency`
);
}
}
if (Array.isArray(depsOrFactory) && isFunction(factory)) {
return asBinding(factory(...depsOrFactory.map(token => getInstance(token))))
}
return asBinding(depsOrFactory as Function)
}
/**
* Bind type to specified value.
*/
export function toValue(value: any) {
if (process.env.NODE_ENV !== 'production') {
if (value === undefined) {
logError(`Please specify some value`);
}
}
return asBinding(() => value);
}
/**
* Bind type to existing instance located by token.
*/
export function toExisting(token: Token) {
if (process.env.NODE_ENV !== 'production') {
if (!isFunction(token)) {
logError(
`Token ${getDebugName(token)} is not a valid dependency injection token`
);
}
}
return asBinding(() => getInstance(token));
}
/* istanbul ignore next */
const IS_BINDING = typeof Symbol === "function" ? Symbol() : "__binding__";
/**
* Mark function as binding function.
*/
function asBinding(binding: any): Function {
binding[IS_BINDING] = true;
return binding;
}
export function registerBinding(definition: Definition) {
let token, binding;
if (Array.isArray(definition)) {
[token, binding = token] = definition;
} else {
token = binding = definition;
}
if (process.env.NODE_ENV !== 'production') {
if (!isToken(token) || !isFunction(binding)) {
logIncorrectBinding(token, binding);
}
}
if (IS_BINDING in binding!) {
addBinding(token, {fn: binding!, onMount: false, onUnMount: false})
} else {
const onMount = 'onMount' in binding!.prototype;
const onUnMount = 'onDisMount' in binding!.prototype;
addBinding(token, {fn: toClass(binding! as new (...args: any) => any), onMount, onUnMount})
}
}
export function registerBindings(definitions: Definition[]) {
definitions.forEach(registerBinding)
}
export { reactModule } from './reactmodule';
export { reactProvider } from './reactprovider';
export { reactService } from './reactservice';
\ No newline at end of file
import { Token } from '../types';
import { registerReducer, registerSagas } from '../registry';
import { registerBinding } from '../bindings';
import { Reducer } from 'redux';
export interface ReactModuleOptReducers {
[key: string]: Reducer;
}
export interface ReactModuleOpts {
token: Token,
reducers?: ReactModuleOptReducers,
sagas?: any[]
}
export const reactModule = (opts: ReactModuleOpts): Function => {
/* @reactModule() usage */
return (target: new (...args: any) => any): Function => {
registerBinding([opts.token, target])
if (typeof opts.reducers !== 'undefined') {
Object.keys(opts.reducers).forEach((reducerName) => {
registerReducer(reducerName, opts.reducers![reducerName]);
})
}
if (typeof opts.sagas !== 'undefined') {
registerSagas(opts.sagas);
}
return target;
}
}
\ No newline at end of file
import React from 'react'
import hoistNonReactStatics from "hoist-non-react-statics"
import { bindings } from '../registry'
import { getInstance } from '../inject'
import { OnMount, OnUnMount } from '../interfaces'
import { Definition } from '../types'
import { registerBindings } from '../bindings'
export interface ReactProviderOpts {
store: any,
defs?: Definition[],
}
export const reactProvider = (opts: ReactProviderOpts) => (Wrapped: any): typeof Wrapped => {
if (typeof opts.defs !== 'undefined') {
registerBindings(opts.defs);
}
class Provider extends React.Component {
displayName = `ReactProvider(${Wrapped.displayName || Wrapped.name})`;
async componentDidMount() {
let barray = bindings();
for (let i = 0; i < barray.length; i++) {
let binding = barray[i];
if (binding[1].onMount) {
let instance = getInstance(binding[0]);
await (instance as OnMount).onMount(opts.store);
}
}
}
async componentWillUnmount() {
let barray = bindings();
for (let i = 0; i < barray.length; i++) {
let binding = barray[i];
if (binding[1].onMount) {
let instance = getInstance(binding[0]);
await (instance as OnUnMount).onUnMount();
}
}
}
render() {
return React.createElement(
Wrapped, this.props
)
}
}
// static fields from component should be visible on the generated Consumer
return hoistNonReactStatics(Provider, Wrapped);
}
\ No newline at end of file
import { Token } from '../types';
import { registerBinding } from '../bindings';
export interface ReactServiceOpts {
token: Token,
}
export const reactService = (opts: ReactServiceOpts): Function => {
return (target: new (...args: any) => any): Function => {
registerBinding([opts.token, target])
return target
}
}
\ No newline at end of file