简体   繁体   中英

Angular 2: importing an export from settings.js into a component file

In my Angular 2 app, I have a settings.js file with various exports that I want to use throughout the application:

exports.httpPort = 9000;
exports.httpsPort = 1435;
exports.segmentID = 1;

I want to export some of these into my ts component file query.component.ts , but I'm at a loss on what the correct syntax to do so is.

I see that many .js files have something along the lines of

var settings = require('../../settings'); 

which grabs the settings file and then

settings.dbConfig

Which calls the export, but it doesn't work on my component file.

This is my project file structure:

component.ts - project/web/src/app/component.ts
-Place where I want to import an export from settings.js.

settings.js - project/server/settings.js
-File where I want to make the export.

First you'll need to set the allowJs flag in your tsconfig.json file to allow js module imports.

// tsconfig.json
{
    "compilerOptions": {
        "allowJs": true
    }
}    

Then you can import your settings.js module in your component

// component.ts
import * as Settings from '../../../server/settings.js';

Now you can use Settings in your component Settings.httpPort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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