gpt4 book ai didi

node.js - serverless webpack 配置,手动添加目录

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:14 24 4
gpt4 key购买 nike

我正在运行以下代码,该代码无法工作,因为当我上传到亚马逊时它找不到模型文件夹。

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;
}

调查问题后,我发现这是因为 models 文件夹没有被 serverless webpack 插件打包。

我最近发现如何在我的无服务器文件中使用此代码强制上传某些包。

webpackIncludeModules:
forceInclude:
- mysql
- mysql2

这似乎只包含包,但是,当我尝试引用模型文件夹以自动包含所有 Sequelize 模型时,我收到一条错误,指出它不是包,这当然是有道理的。

这确实给我留下了一个问题:如何让它打包模型目录,而无需手动为每个模型执行 require 操作。我编写了一个动态函数来在运行时获取它们并将其导入到sequelize。

有关插件的信息在这里( https://github.com/serverless-heaven/serverless-webpack ),我浏览了所有内容,但似乎找不到答案。

使用无服务器打包的输出如下所示,缺少包含我的所有 Sequelize 模型的模型文件夹。

enter image description here

我在做 webpack 之前的主目录是这样的。

enter image description here

这也是我的 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/
}
]
}
};

最佳答案

您可以使用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, {})
]
};

确保从正确的文件夹导入模型,因为您是从相对路径导入的。如果您的 bundle 位于不同的文件夹中,这可能会改变。

关于node.js - serverless webpack 配置,手动添加目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com