How can I use javascript library such as moment.js

2020-06-06 08:19发布

问题:

What is the recommended way to use native javascript libraries in react native? Are there any specific restrictions?

回答1:

Easy peasy! From the root of your project just run:

npm install moment --save

Then you can import it in your code:

import moment from 'moment';
var now = moment().format();

The restrictions would be anything that tries to "reach out" to the browser (which doesn't exist in this context). That's why there's polyfills for things like XHR.

The official documentation has examples on how to use the moment library



回答2:

Some of the moment methods work in React Native and others don't. I suspect it has to do with listeners.

I can use moment for formatting:

moment(new Date()).format("YYYY-MM-DD hh:mm:ss")

But not for active formatting:

moment(new Date()).format("YYYY-MM-DD hh:mm:ss").fromNow()


回答3:

to use a npm library just use this command with the respective library name

npm install moment --save

eg.) npm install {your library name here} --save

then just import in your class and use

import moment from 'moment';


回答4:

It looks like as of right now, some npm modules are not compatible with the packager. Haven't really dug into why yet, but what I've been resorting to doing is having a vendor folder and copying over the web version but at the top specifically putting

/** * @providesModule moment */

And at the bottom changing it up to:

module.exports = moment;

Not sure if this is the correct way yet, but the packaging is still pretty new to everyone.



回答5:

If you specifically want to use moment.js in react or react native, have a look at react-moment, a react component for the moment library, at https://github.com/headzoo/react-moment.

To use react-moment in react native, run:

npm install --save moment react-moment

Then in the file you want to use moment:

import Moment from 'react-moment';

Finally, use it as desired, for example:

<Moment element={Text} fromNow>
    { post.datePublished }
</Moment>

The prop element={Text} is specifically for react native. It ensures that the resulting string is rendered in a Text component. Without this, react native would throw an error.