![](/img/trans.png)
[英]Serverless with node.js doesn't deploy some dependencies node_modules
[英]NOde.js/Express App can't find some node_modules
我在我的應用程序中使用了幾個Node / Express模塊,只要我執行const module = require('module');
每個模塊的所有功能都可以正常工作const module = require('module');
。 我不需要為這些模塊定義靜態路徑為app.use(express.static(path.join(__dirname, 'public')));
。
但是,對於sweetalert模塊,如果我在我的layout.pug (基礎哈巴狗文件) script(src="/node_modules/sweetalert/dist/sweetalert.min.js")
,除非出現404錯誤(未找到),否則我在app.js中包括以下靜態路徑: app.use("/node_modules", express.static(__dirname + "/node_modules"));
。
我的問題是:這是正常的行為還是我沒有做對的事情? (我有點困惑,為什么我必須為我使用的幾個模塊之一定義靜態路徑。
這是怎么回事:
app.use(express.static(path.join(__dirname, 'public')));
聲明瀏覽器可以訪問公用目錄。 您應該將所有前端資源放在該文件夾中。 這將有助於區分可從服務器訪問的內容和可從客戶端訪問的內容。
當您引用script(src="/node_modules/sweetalert/dist/sweetalert.min.js")
,瀏覽器將拋出404,因為該文件不在公共目錄中,因此瀏覽器無法訪問。
添加此行app.use("/node_modules", express.static(__dirname + "/node_modules"));
“修復”您的問題,但現在將所有node_modules公開給瀏覽器。 這可能不是一個好主意,我敢肯定,安全專家可以詳細說明為什么不應該這樣做。
我將如何解決此問題:瀏覽您的.pug
代碼,查看前端所需的任何資源。 然后將它們復制到公用文件夾,並修復您的引用以使用資源的副本。
這是我用來將資源從node_module目錄移動到public / assets目錄的腳本示例:
build.js:
const path = require('path');
var fs = require('fs');
const ASSETS = [
'jquery/dist/jquery.min.js',
'sweetalert/dist/sweetalert.min.js'
];
if (!fs.existsSync('./public/assets')){
fs.mkdirSync('./public/assets');
}
ASSETS.map(asset => {
let filename = asset.substring(asset.lastIndexOf("/") + 1);
let from = path.resolve(__dirname, `./node_modules/${asset}`)
let to = path.resolve(__dirname, `./public/assets/${filename}`)
if (fs.existsSync(from)) {
fs.createReadStream(from).pipe(fs.createWriteStream(to));
} else {
console.log(`${from} does not exist.\nUpdate the build.js script with the correct file paths.`)
process.exit(1)
}
});
然后我將package.json更新為包含在腳本中:
package.json:
"scripts": {
"build": "node ./build.js || true",
"start": "node ./bin/www"
}
然后在我的任何視圖頁面中,我都使用新路徑引用資源
random.pug:
script(src="/assets/jquery.min.js")
script(src="/assets/sweetalert.min.js")
最后,在部署應用程序之前,現在必須運行以下命令: npm run build
然后npm start
僅當前端資源發生更改時,才需要運行build命令。 因此,如果您僅使用sweetalert.min.js
,則僅在首次運行應用程序時才需要運行構建。 如果以后再添加另一個資源aNewResource.js
,則需要更新build.js
文件並再次運行npm run build
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.