【发布时间】:2022-04-04 17:46:03
【问题描述】:
我在一个无服务器项目中使用 Sequelize,它使用 Webpack 将函数文件捆绑到一个脚本中。
我有一个models 文件夹,其中包含模型定义:
models/ExampleModel.js
import { DataTypes, Model } from 'sequelize';
module.exports = sequelize => {
class ExampleModel extends Model {
static associate(models) {
// handle associations
}
}
ExampleModel.init({
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
...
}, {
sequelize,
});
return ExampleModel;
}
然后我有一个models/index.js 文件,其中包含一个加载器来导入这些文件并调用associate 函数来建立关联:
import fs from 'fs';
import path from 'path';
import { Sequelize } from 'sequelize';
const sequelize = new Sequelize(process.env.DB_URL);
const base = path.resolve('src/models')
const db = {};
fs
.readdirSync(base)
.filter((file) => {
console.log(file)
const returnFile = (file.indexOf('.') !== 0)
&& (file !== 'index.js')
&& (file.slice(-3) === '.js');
return returnFile;
})
.forEach((file) => {
const filepath = path.join(base, file);
const model = require(filepath)(sequelize)
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
export default db;
问题是这个函数显然是在运行时执行的(当你尝试导入模型时),所以 Webpack 无法识别模型文件是必需的并且没有将它们包含在构建中。
为了解决这个问题,我尝试将以下内容添加到我的 Webpack 配置中:
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: 'src/shared/v3/models', to: 'src/models' },
]
}),
...
]
当我查看 Webpack 的输出时,它已成功将模型目录复制到 src/models:
.webpack/test-models
└── src
├── models
│ ├── ExampleModel.js
│ └── index.js
└── scripts
├── test-models.js
└── test-models.js.map
但是,当 test-models.js 运行时,它会失败并出现错误:
错误:找不到模块'/Users/redacted/.webpack/test-models/src/models/ExampleModel.js
index.js的过滤函数中的console.log成功记录了所有的模型文件名,而且文件存在,所以我不知道为什么require调用找不到文件。
运行下面成功列出错误信息中的文件内容:
$ cat /Users/redacted/.webpack/test-models/src/models/ExampleModel.js
import { DataTypes, Model } from 'sequelize';
module.exports = sequelize => {
class ExampleModel extends Model {
...
我检查了复制文件的权限,它们都是-rw-r--r--,所以脚本应该可以读取。
【问题讨论】:
-
您找到解决方案了吗?我也有同样的问题。
-
我最终只是编写了一个快速的独立脚本来获取目录列表,构建一个
index.js单独导入每个文件(硬编码)然后导出,并将其添加到构建管道
标签: node.js webpack sequelize.js serverless-framework