我有一个关于将node_modules包含到HTML网站的最佳实践的问题。
假设我在node_modules文件夹中有Bootstrap。现在对于网站的生产版本,我将如何包括位于node_modules文件夹内的引导脚本和CSS文件?将Bootstrap留在该文件夹中并执行如下操作是否有意义?
<script src="./node_modules/bootstrap/dist/bootstrap.min.js"></script>
或者我必须在gulp文件中添加规则,然后将这些文件复制到dist文件夹中?或者最好让gulp以某种方式完全从我的HTML文件中删除本地引导,并将其替换为CDN版本?
我做了下面的更改,以AUTO-INCLUDE索引html中的文件。因此,当你在文件夹中添加一个文件时,它将自动从文件夹中取出,而不必将该文件包含在index.html中
//// THIS WORKS FOR ME
///// in app.js or server.js
var app = express();
app.use("/", express.static(__dirname));
var fs = require("fs"),
function getFiles (dir, files_){
files_ = files_ || [];
var files = fs.readdirSync(dir);
for (var i in files){
var name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()){
getFiles(name, files_);
} else {
files_.push(name);
}
}
return files_;
}
//// send the files in js folder as variable/array
ejs = require('ejs');
res.render('index', {
'something':'something'...........
jsfiles: jsfiles,
});
///--------------------------------------------------
///////// in views/index.ejs --- the below code will list the files in index.ejs
<% for(var i=0; i < jsfiles.length; i++) { %>
<script src="<%= jsfiles[i] %>"></script>
<% } %>
这是我在我的快速服务器上设置的:
// app.js
const path = require('path');
const express = require('express');
const expressApp = express();
const nm_dependencies = ['bootstrap', 'jquery', 'popper.js']; // keep adding required node_modules to this array.
nm_dependencies.forEach(dep => {
expressApp.use(`/${dep}`, express.static(path.resolve(`node_modules/${dep}`)));
});
<!-- somewhere inside head tag -->
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.css" />
<!-- somewhere near ending body tag -->
<script src="jquery/dist/jquery.js" charset="utf-8"></script>
<script src="popper.js/dist/popper.js" charset="utf-8"></script>
<script src="bootstrap/dist/js/bootstrap.js" charset="utf-8"></script>
祝你好运…