1

I have a Webpack angular 2 application and I have a date picker module dependency with a library using Moment. The thing is that if I don't import it like :

<script src="./../node_modules/moment/min/moment.min.js"></script>

a moment is not defined error is raised if I want to use it. I tried to import moment with require but it's not taken into account.

The problem is that the script src tag works in local but in the webpack builded version we need to deploy the path with node_modules doesn't exist anymore. Is there a way to do it other than hard paste moment.min.js in a lib folder?

1 Answer 1

2

Add the following code in webpack.conf.js:

resolve: {
    alias: {
        'moment': 'moment/min/moment.min'
    }
}

Now you can simply do, require('moment') in your js file.

Note: By default webpack searches the file in node_modules folder. You can instruct it to look into specific places using modules property of resolve object. The resulting code would look like:

resolve: {
    modules: ['lib/','some_folder/node_modules'...],
    alias: {
        'moment': 'moment/min/moment.min'
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer, the app compiles and it seems to be considered but the datepicker still doesn't want to consider it otherwise than with an import :(
@guigui Can you share the error code? Also, what's the context you're passing in config file?
So in my app.component.ts I did put a require('moment') at the top, I've also put the alias: { 'moment': 'moment/moment' } in the resolve of the webpack conf file, and for the error message I get a Error in ./Ng2DatetimePickerComponent class Ng2DatetimePickerComponent - inline template:36:4 caused by: moment is not defined
Now you can simply do, require('moment') in your js file - no, you can't. Like most libraries, it is UMD module that doesn't expose a global in modular environment. So it should be imported in files where it is used. So I don't see why alias should be used here. It should be treated like any other JS library, probably with TS types.
@guigui Don't rely on globals. Do const moment = require('moment') in files where it is used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.