Giter Club home page Giter Club logo

ember-cli-prop-types's Introduction

PropTypes Icon

Latest NPM release Ember Observer Score Dependencies Dev Dependencies

Ember CLI PropTypes

This addon makes the prop-types library available for React style props validation in your Ember application. The addon itself is very simple, it includes:

  1. AMD compatible import of prop-types library (prod optimized import weight of only 0.12KB gzipped).
  2. Ember Component reopen in dev builds to call checkPropTypes, see the component-prop-types initializer (Component reopen stripped for production builds).

Props validations and the validators themselves are all provided by the prop-types library.

Install

ember install ember-cli-prop-types

Props Validation

Import PropTypes into your component JS files and define a propTypes property to perform validation on passed props:

// your-component.js
import Component from 'ember-component';
import PropTypes from 'prop-types';

export default Component.extend({
  // Define prop types for your passed properties here
  propTypes: {
    title: PropTypes.string.isRequired,
    pages: PropTypes.number,
    isLatest: PropTypes.bool
  }
});

The prop-types library will validate that any props passed into your component match the type specified in propTypes. See the prop-types Documentation for details on defining propTypes for your components.

Validating Ember-Specific Classes/Concepts

You can validate the majority of Ember classes or other Ember-specific concepts via the instanceOf type checker. We have added specific support for Ember.Array and will continue to add support for Ember classes that cannot be validated using the library as-is.

import Component from 'ember-component';
import EmberObject from 'ember-object';
import DS from 'ember-data';
import PropTypes from 'prop-types';
const { PromiseArray } = DS;

export default Component.extend({
  propTypes: {
    post: PropTypes.instanceOf(EmberObject),
    relatedPosts: PropTypes.instanceOf(PromiseArray),
    authors: PropTypes.emberArray.isRequired,
    comments: PropTypes.emberArray,
    leaveCommentClosureAction: PropTypes.func
  }
});

Ember-Specific Checkers:

  • PropTypes.emberArray

Destructured Imports

Destructuring imports is also supported:

import Component from 'ember-component';
import { string, number, bool, func } from 'prop-types';

export default Component.extend({
  propTypes: {
    title: string.isRequired,
    pages: number,
    isLatest: bool,
    someAction: func
  }
});

Props Default Values

This addon adds the ability to set a default value for passed props through a getDefaultProps method. This method should return an object with the default props values:

import Component from 'ember-component';
import { string, number, bool } from 'prop-types';

export default Component.extend({
  propTypes: {
    title: string.isRequired,
    pages: number,
    isLatest: bool
  },
  getDefaultProps() {
    return {
      title: 'Ambitious Props',
      pages: 1,
      isLatest: false
    };
  }
});

During component initialization, if a prop with a configured default is undefined, it will be set to the returned default value. This can be especially helpful when working with dynamic values or the component helper.

The getDefaultProps method is run during production builds.

Lifecycle Hook Super Calls

This addon calls props validation and default value assignments in the didReceiveAttrs and init lifecycle hooks. Per the Ember.js docs, if you need to define additional behavior in these hooks you must call this._super(...arguments):

export default Component.extend({
  propTypes: {
    someString: PropTypes.string
  },
  getDefaultProps() {
    return {
      someString: 'Default Value'
    }
  },

  init() {
    this._super(...arguments);
    // your component code
  },
  didReceiveAttrs() {
    this._super(...arguments);
    // your component code
  }
})

In Production

Although props validation is only run in development builds, this addon must be included for production builds as well. During production builds the prop-types library is not imported. Instead a set of shims is imported for the props validators so that the import statements do not throw errors. Prod weight for the addon is 0.29 KB (0.12 KB gzipped).

The call to PropTypes.checkPropTypes is automatically stripped in production builds as well using UglifyJS's compress configurations. If you would like to disable this additional stripping you can configure the addon to skip it in your ember-cli-build.js configs (Note that even if you disable the code stripping props validations will still only be run in dev builds).

The getDefaultProps method is run during component init in production builds. If you would prefer not to enable this method, you can configure the addon to strip it out:

// ember-cli-build.js
module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    emberCliPropTypes: {
      compress: false, // Setting to false will disable code stripping
      getDefaultProps: false // Setting to false will strip `getDefaultProps` feature
    }
  });

  return app.toTree();
};

Contributing

If you'd like to contribute, please read our contribution guidelines and then get cracking!

Please report bugs using the issues tab.

ember-cli-prop-types's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

ember-cli-prop-types's Issues

PropTypes.emberArray.isRequired is undefined in test env

Hi!

PropTypes.emberArray.isRequired is undefined in test env

I get the following:

testem.js:1025 TypeError: Cannot read property 'isRequired' of undefined
    at Module.callback (component.js:4)
    at Module.exports (loader.js:106)
    at requireModule (loader.js:27)
    at Class._extractDefaultExport (resolver.js:382)
    at Class.resolveOther (resolver.js:79)
    at Class.superWrapper (ember.debug.js:40872)
    at Class.resolve (ember.debug.js:5317)
    at resolve (ember.debug.js:2713)
    at Registry.resolve (ember.debug.js:2172)
    at Registry.resolve (ember.debug.js:2176)
  • OS: macOS Sierra 10.13.3
  • Ember CLI 2.12.2
  • Node 8.8.0 with npm 5.6.0
  • Browser: Chrome 64.0.3282.167

Add `getDefaultProps` Functionality

We need to set up the ability to set default values for properties passed into components. These defaults will only be utilized in cases where a developer has not supplied a value to any properties which have defaults defined.

Utilizing this should be similar to defining prop types; on a component, an object that defines default prop values can be created which will automatically get looked up by getDefaultProps. The Component code will automatically take care of the work of checking for the default values and using them when no value has been passed in.

Example:

import Component from 'ember-component';
import hbs from 'htmlbars-inline-precompile';
import PropTypes from 'prop-types';

export default Component.extend({
  
  defaultProps: {
    bar: 5,
    greeting: 'Hello, ',
    name: 'smart and attractive developer'
  }

  propTypes: {
    bar: PropTypes.number,
    greeting: PropTypes.string,
    name: PropTypes.string
  },

  layout: hbs`{{greeting}}{{name}}! You are looking like {{bar}} million major currency units today!`

});

Under the hood, we will need to make additions to our Component initializer to set the default values from defaultProps to their corresponding properties on the component itself.

Uncaught ReferenceError: DEVELOPMENT is not defined

Summary

With a new Ember app and installing ember-cli-prop-types, I get an error in the console Uncaught ReferenceError: DEVELOPMENT is not defined and the app will not load.

ember-cli: 2.13.1
node: 6.10.2
os: darwin x64

>ember new prop-types-test
>ember serve - app loads as expected
>ember install ember-cli-prop-types
>ember serve - error

Test Inline Replace Variables Babel Plugin

Hello, friends!

Summary

To enable code stripping we use build variables, which means that in Dev builds we have to use the contentFor hook to inject a script into the head of any consuming app and add the build variables as globals to the window. This is ๐Ÿ˜ข.

This Babel plugin appears to be able to replace variables with literal values inline: https://github.com/wssgcg1213/babel-plugin-inline-replace-variables. We should test this with the Ember CLI pipeline. If it works we could add the plugin to consuming builds and inline replace our build variables with their values so we don't have to mess with UglifyJS settings in prod or do the contentFor hack in dev.

Extending `PropTypes` with Ember specific types

Hey @evrowe,

I'm just starting to use the library and I'm really digging it. I like having that explicit contract for a component right in the code.

One thing I have run into is that the prop types that React uses don't have any idea of Ember constructs. For example, Ember uses an Ember.Object to represent a PromiseArray. So when using PropTypes.array for a collection of DS.Model returned from a route it will fail.

I would like to build this into this library and I am hoping to discuss adding Ember specific extensions to the PropTypes object. These could live on PropTypes.ember.* so that the component is explicitly stating 'This is an Ember related prop'.

For example, some proposed additions I think would be useful:

  1. PropTypes.ember.array: Checks if the given component prop is an Ember.Array via Ember.isArray
  2. PropTypes.ember.model($MODEL_CLASS): Checks if the given component prop is an instance of the given DS.Model class.

Is this of interest, I'd be happy to put together a PR that takes a crack at the above!

Update project to use Node 10/npm6

Summary

Currently this repo's travis configuration is set up to use Node 6/npm 3. We need to modernize the test configuration to use Node 10/npm6.

Is it possible to use `PropTypes.shape` with an Ember Object?

Hello!

I was wondering if there's any to use PropTypes.shape with an EmberObject?

I know you can use instanceOf to check that a thing is an EmberObject, but I'd also like to still assert against its internal properties as well.

Summary

When I use shape to describe an Ember.Object, I get failed prop types for the individual keys, even though I can verify the keys are correct.

Example

For example, let's say I have an Ember model:

export default DS.Model.extend({
  type: DS.attr('string'),
  items: DS.attr(),
});

I'd like to check that using prop-types, like so:

export default P.shape({
  type: P.oneOf([
    'conversation',
    'route'
  ]).isRequired,

  items: P.oneOf([
    P.arrayOf(Message),
    P.string
  ]).isRequired,
});

However, when I try to use this type in a component by passing in something like:

{
  type: "conversation",
  ...
}

I see the following failed prop-type:

image

Environment Information

Here's my setup:

  • OS: masOS El Capitan
  • Ember + Ember CLI Version: Ember 2.15
  • Node/NPM Version: Node 7, npm 3
  • Browser: Chrome, latest

Addon does not work with ember-cli 3.4.0-beta.2 or above; `NODE_ENV is not defined`

Hello!

Summary

ember-cli-prop-types does not work with ember-cli 3.4.0-beta.2 or above.

Description + Repro Steps

I tried to update ember-cli (either only ember-cli or using ember-cli-update [which updates more dependencies]) to the newest version (3.4.3). But after update, I see an error in my app: ReferenceError: NODE_ENV is not defined.

Uncaught ReferenceError: NODE_ENV is not defined
    at Object.initialize (component-prop-types.js:21)
    at index.js:91
    at Vertices.each (dag-map.js:188)
    at Vertices.walk (dag-map.js:117)
    at DAG.each (dag-map.js:62)
    at DAG.topsort (dag-map.js:68)
    at Class._runInitializer (index.js:112)
    at Class.runInitializers (index.js:88)
    at Class._bootSync (application.js:431)
    at Class.domReady (application.js:385)

ember-cli version 3.3.0 or 3.4.0-beta.1 works correctly. ember-cli 3.4.0-beta.2 or 3.4.2 or above does not work with ember-cli-prop-types

It looks that NODE_ENV, INCLUDE_GET_DEFAULT_PROPS and other variables are not replaced by babel-plugin-inline-replace-variables after ember-cli upgrade.
If I moved configuration of babel-plugin-inline-replace-variables from preprocessTree to the options object (like in the example in the babel/ember-cli-babel https://github.com/babel/ember-cli-babel#options ), then problem disappeared. Of course - env or process.env.EMBER_ENV is not defined yet. But also helped moving this configuration from preprocessTree to the included function (I guess that order of called functions was changed in new ember - it's only my guess).

Environment Information

Here's my setup:

  • OS: Antergos running version 4.18.12-arch1-1-ARCH
  • ember-cli: 3.4.3
  • ember-cli-prop-types: 1.5.0
  • Node: 10.11.0 with npm 6.4.1, yarn 1.9.4, bower 1.8.4
  • Browser: Chrome 69.0.3497.100-1

Is this addon expected to ship in production?

I have read through the code and seems that this addon is unconditionally including the proptypes library and reopening components, unless I've missed something.

Is this intended? I think it should only run in development and tests but be removed in production.

Disclaimer: i've never used PropTypes in react, so I don't know if there is any reason to run it in production too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.