本文介绍了如何在节点迁移中使用TypeScrip作为编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我的迁移脚本如下:

const bluebird = require("bluebird");
const mongoose = require("mongoose");
mongoose.Promise = bluebird;
mongoose.connect("mongodb://localhost:27017/app", { useMongoClient: true    });

const schema = {    
    uid: {  
        type: String,   
    },  

    parentID: { 
        type: String,   
    },  

    name: { 
        type: String,   
    },  

    displayName: {  
        type: String,   
    },  

    createdAt: {    
        type: Date, 
    },  

    modifiedAt: {   
        type: Date, 
    }   
};  

const FolderSchema = new mongoose.Schema(schema);   
const FolderModel = mongoose.model("folders", FolderSchema);    


// initial folders  
const folders = [   
    { uid: "", parentID: "", name: "folder1", displayName: "Folder 1" },    
    { uid: "", parentID: "", name: "folder2", displayName: "Folder 2" },    
];  

function up(next) { 
    const promises = [];    
    folders.map((folder, index) => {    
        promises.push(FolderModel.create(folder));  
    }); 

    bluebird.all(promises).then((res) => {  
        mongoose.connection.close();    
        next(); 
    }); 
}   

function down(next) {   
    const promises = [];    
    folders.map((folder, index) => {    
        promises.push(FolderModel.remove({ name: folder.name }));   
    }); 

    bluebird.all(promises).then((res) => {  
        next(); 
    }); 
}   

module.exports.up = up;
module.exports.down = down;

我使用node-migrate进行迁移,在高级迁移创建部分,它显示:

最后,如果您想要使用较新的ECMAScript功能,或像TypeScrip这样的语言插件,对于迁移,您可以使用编译器标志。

但是,当我使用--编译器="ts:tyescript"运行脚本时,即使我已经安装了tyescript,它也总是会抛出错误。

    C:UsersjohnWorkspaceapp
ode_modulesmigratelib
egister-compiler.js:12
  require(mod)({
              ^

TypeError: require(...) is not a function
    at registerCompiler (C:UsersjohnWorkspaceapp
ode_modulesmigratelib
egister-compiler.js:12:15)
    at Object.<anonymous> (C:UsersjohnWorkspaceapp
ode_modulesmigrateinmigrate-up:57:3)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

推荐答案

您可以执行以下操作以使ts-nodenode-migrate一起工作。

  1. 创建一个简单的js文件,包含:

    const tsNode = require('ts-node');
    
    module.exports = tsNode.register;
    
  2. 执行迁移时将编译器标志与上述文件一起传递:

    migrate up --compiler="ts:./typescript-compiler.js"

这应该足以让您运行文字稿迁移。

这篇关于如何在节点迁移中使用TypeScrip作为编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 05:46