guigui
guigui

Reputation: 103

Webpack import a node module in script

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?

Upvotes: 1

Views: 5930

Answers (1)

Apoorv Joshi
Apoorv Joshi

Reputation: 399

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'
    }
}

Upvotes: 2

Related Questions