简体   繁体   English

节点JS Express包含/导入/导出

[英]Node JS Express include/import/export

Okay, so basically I'm trying to learn and get a hang on the export/import modules in Node. 好的,基本上,我想尝试学习并了解Node中的导出/导入模块。 I have created a app.js which contains, everything. 我创建了一个包含所有内容的app.js To make the app.js file a little cleaner and more readable I'm trying to include a .js file from another folder ( middleware/sass.js) , how would I do that? 为了使app.js文件更整洁,更易读,我尝试从另一个文件夹( middleware/sass.js)包含.js文件,我该怎么做?

My sass.js file looks like this: 我的sass.js文件如下所示:

let sassMiddleware = require('node-sass-middleware');

app.use(
    sassMiddleware({
        src: path.join(__dirname, 'resources/scss'),
        dest: path.join(__dirname, 'public/css'),
        debug: true,
        indentedSyntax: false,
        outputStyle: 'compressed',
        prefix: '/css'
    })
);

How do I "include" that in app.js without having it all there? 如何在不包含所有内容的情况下将其“包含”到app.js I would say I try to do something like the PHP include() 我会说我尝试做类似PHP include()事情

You need to either have application instance in separate module, so it could be imported in multiple places: 您需要将应用程序实例放在单独的模块中,以便可以在多个位置导入它:

index.js index.js

require('./sass');
const app = require('./app');
app.listen(...);

app.js app.js

...
const app = express();
module.exports = app;

sass.js sass.js

const app = require('./app');
...
app.use(...);

Or use dependency injection and wrap all parts that depend on application instance with a function: 或使用依赖注入并使用函数包装依赖于应用程序实例的所有部分:

index.js index.js

const app = require('./app');
require('./sass')(app);
app.listen(...);

sass.js sass.js

...
module.exports = app => {
  app.use(...);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM