简体   繁体   English

使用npm导入html中的javascript

[英]Import javascript in html with npm

I am trying to add this github component to my project. 我正在尝试将此github 组件添加到我的项目中。 I followed the instruction to use npm 我按照指示使用npm

npm install pikaday --save

and the pikaday and moment modules are in the node module folder, but when I run my html file: 和pikaday和moment模块位于node module文件夹中,但是当我运行html文件时:

<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: 然后在您的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. 据我所知,如果您要在npm上使用,则需要使用webpack之类的其他框架来用整个js代码构建一次javascript文件,因为不应该将node_modules目录部署到服务器上。

The snippet var Pikaday = require('pikaday') doesn't work in browsers, only over the node.js server. 片段var Pikaday = require('pikaday')在浏览器中不起作用,仅在node.js服务器上有效。

if you don't want to build a bundle with your js, you may just download the files and configure into your assets 如果您不想与js建立捆绑包,则可以下载文件并配置到资产中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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