我正在运行的以下代码无法正常工作,因为当我上传到亚马逊时它找不到模型文件夹。
exports.setModels = function(connection,modelPath){
//Import all the known models for the project.
//Proof of Stage being set.
console.log("stage for models="+stage);
const fs = require('fs');
const dir = modelPath;
var models = {};
//@JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log("file="+file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
var modelPath = "../models/"+file; //default assumes same directory that was used to scan.
if(process.env.DOMAIN_NAME){ //If this enviroment variable is detected then change the modelPath.
modelPath = "../../../../models/"+file;
}
models[name] = connection.import(modelPath);
})
return models;
}
在调查了这个问题后,我发现它是因为模型文件夹没有被 serverless webpack 插件打包。
我最近发现了如何在我的无服务器文件中使用此代码强制某些包上传。
webpackIncludeModules:
forceInclude:
- mysql
- mysql2
然而,这似乎只包含包,当我尝试引用模型文件夹以自动包含我所有的续集模型时,我收到一个错误,说它不是包,这当然是有道理的。
这确实给我留下了一个问题,即如何在不手动为每个模型执行 require 的情况下打包模型目录。我编写了一个动态函数来在运行时获取它们并将其导入到续集。
关于插件的信息在这里(https://github.com/serverless-heaven/serverless-webpack),我浏览了所有内容,但似乎找不到答案。
使用无服务器打包的输出如下所示,缺少包含我所有续集模型的模型文件夹。
我在做 webpack 之前的主目录是这样的。
这也是我的 webpack.config.js。
const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: slsw.lib.entries,
target: "node",
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externals: [nodeExternals()],
// Run babel on all .js files and skip those in node_modules
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: __dirname,
exclude: /node_modules/
}
]
}
};