Create-React-App with Moment JS: Cannot find modul

2019-01-26 10:30发布

问题:

Just ran an npm update on my web application and now Moment JS appears to be failing with the following message:

Error: Cannot find module "./locale"
\node_modules\moment\src\lib\moment\prototype.js:1
> 1 | import { Moment } from './constructor';

Not sure what version of Moment JS I had prior to my update, but my application has been working for months.

I created another react app and ran an npm install moment --save and modified the source to display the time and ended up with the same error described above.

Not sure if there is a fail-proof way to integrate Moment JS using Create-React-App currently short of ejecting to manage the webpack settings myself, but I really don't want to do this. Anyone else seeing these issues or having success? If so, a short write up would go along way to helping out.

回答1:

Appears this has already been identified as an issue for Moment JS version 2.19. If you have upgraded to 2.19 run npm install moment@2.18.1 to revert back to previous version until it is fixed!

See thread: https://github.com/moment/moment/issues/4216



回答2:

The answer above, though I have no doubt works for some, does not work for me. The solution I found is fairly quick and easy, but is a little more complicated than simple downgrading.

This problem originates as a result of and can be fixed with webpack. So we're going to have to add a few lines of code to our webpack.config.js file. If you don't have one yet, you can add one to the root webpack directory:

YOURAPPNAME/node-modules/webpack/

So now that you're inside your webpack.config.js file, you need to add a few lines of code. Just copy and paste this inside the new file or adapt it to the code you already have in webpack.config.js.

module.exports = {
    resolve: {
        alias: {
            moment$: 'moment/moment.js'
        }
    }
};

Your import statement of moment in your index.js (or otherwise named) file should look like this:

import moment from 'moment'

You should now be able to use moment completely normally. For example:

var tomorrow = moment().add(1, "day")