我运行的以下代码无法正常工作,因为当我上传到亚马逊时无法找到models文件夹。
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;
}
在调查了这个问题之后,我发现了它,因为无服务器webpack插件没有打包models文件夹。
我最近发现了如何在我的无服务器文件中强制使用此代码上传某些软件包。
webpackIncludeModules:
forceInclude:
- mysql
- mysql2
这似乎只包括包,当我尝试引用models文件夹自动包含我所有的sequelize模型时,我得到一个错误,说它不是包,当然这是有道理的。
这确实让我产生了如何在不手动为每个模型执行的情况下打包模型目录的问题。我编写了一个动态函数来在运行时获取它们并将其导入sequelize。
关于插件的信息在这里(https://github.com/serverless-heaven/serverless-webpack),我仔细查看了所有内容,但似乎无法找到答案。
使用无服务器的打包输出如下所示,缺少所有续集模型的models文件夹。
在做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/
}
]
}
};
答案 0 :(得分:0)
您可以使用copy-webpack-plugin来包含模型而不是引用。
const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require('copy-webpack-plugin');
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/
}
]
},
plugin: [
new CopyWebpackPlugin(filesToCopy, {})
]
};
确保从相对路径导入时从右侧文件夹导入模型。如果您的捆绑包位于不同的文件夹中,则可能会更改。