简体   繁体   中英

Import javascript in html with npm

I am trying to add this github component to my project. I followed the instruction to use npm

npm install pikaday --save

and the pikaday and moment modules are in the node module folder, but when I run my html file:

<body>
<input type="text" id="datepicker" value="9 Jun 2016">
<script src="pikaday.js"></script>
<script src="moment.js"></script>
<script>
    var Pikaday = require('pikaday')
    var picker = new Pikaday({
        field: document.getElementById('datepicker'),
        format: 'D MMM YYYY',
        onSelect: function() {
            console.log(this.getMoment().format('Do MMMM YYYY'));
        }
    });
</script>
</body>

I got the following error:

GET http://localhost:3000/pikaday.js 
(index):14 GET http://localhost:3000/moment.js 
(index):17 Uncaught ReferenceError: Pikaday is not defined
    at (index):17

I change the path to

<script src="/node_modules/pikaday/pikaday.js"></script>

but got the same error

Your going to need to make that available as a static file. If you're using express:

app.use('/static/pikaday/pikaday.js', express.static('./node_modules/pikaday/pikaday.js')

Then in your html:

<script src="/static/pikaday/pikaday.js"></script>

As far as I know is if you'll use by npm, you'll need to use other framework like webpack to build once javascript file with your whole js code, because the node_modules dir should not be deployed to your server.

The snippet var Pikaday = require('pikaday') doesn't work in browsers, only over the node.js server.

if you don't want to build a bundle with your js, you may just download the files and configure into your assets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM