노드에서 상수를 공유하는 방법JS 모듈?
현재 이 작업을 하고 있습니다.
foo.discloss(후우)
const FOO = 5;
module.exports = {
FOO: FOO
};
그리고 그것을 에 사용하다bar.js
:
var foo = require('foo');
foo.FOO; // 5
더 좋은 방법이 있을까요?내보내기 객체에 상수를 선언하는 것은 어색합니다.
제 생각에 활용은 드라이어와 선언적인 스타일을 가능하게 합니다.원하는 패턴은 다음과 같습니다.
./lib/constants.js
module.exports = Object.freeze({
MY_CONSTANT: 'some value',
ANOTHER_CONSTANT: 'another value'
});
./lib/some-module.js
var constants = require('./constants');
console.log(constants.MY_CONSTANT); // 'some value'
constants.MY_CONSTANT = 'some other value';
console.log(constants.MY_CONSTANT); // 'some value'
오래된 퍼포먼스 경고
다음 문제는 2014년 1월에 v8에서 수정되었으며 대부분의 개발자와는 더 이상 관련이 없습니다.
false에 쓰기 가능한 설정과 개체를 사용하는 설정 모두 유의하십시오.freeze는 v8 - https://bugs.chromium.org/p/v8/issues/detail?id=1858 및 https://jsben.ch/AhAVa에서 퍼포먼스에 큰 영향을 미칩니다.
말하면, 「 」입니다.const
ECMAScript 。지금까지 "" "Common" "Common" "하여 해당 할 수 객체입니다.JS " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " 같은 을 필요로 하는 될지는 가능합니다 ( " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
공유할 수 있는 실제 상수를 얻으려면 , 및 을 확인하십시오.설정했을 경우writable: false
"어느 쪽인가"
조금 장황하지만(이것마저도 약간의 JS로 변경할 수 있습니다) 상수 모듈에 대해 한 번만 수행하면 됩니다.방법을 으로 Atribute가 됩니다.false
로 Atribute가 됩니다true
)
래, 정, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신, 신value
★★★★★★★★★★★★★★★★★」enumerable
는 writable
★★★★★★★★★★★★★★★★★」configurable
상태가 false
알기 쉽게 포함시켰을 뿐이에요.
업데이트 - 바로 이 사용 사례에 맞게 도우미 기능이 있는 새 모듈(노드 상수)을 만들었습니다.
constants.js -- 양호
Object.defineProperty(exports, "PI", {
value: 3.14,
enumerable: true,
writable: false,
configurable: false
});
constants.js --더 나은
function define(name, value) {
Object.defineProperty(exports, name, {
value: value,
enumerable: true
});
}
define("PI", 3.14);
script.discripts.discripts: 스크립트
var constants = require("./constants");
console.log(constants.PI); // 3.14
constants.PI = 5;
console.log(constants.PI); // still 3.14
ES6 방식
foo.disc로의 내보내기
const FOO = 'bar';
module.exports = {
FOO
}
import in bar.displaces
const {FOO} = require('foo');
으로 내보낼 수 .global.FOO = 5
그러면 반환값을 저장하지 않고 파일을 요구하기만 하면 됩니다.
근데 진짜 그러면 안 돼요.사물을 적절하게 캡슐화하는 것은 좋은 일이다.당신은 이미 올바른 생각을 가지고 있으니, 당신이 하고 있는 일을 계속하세요.
이전 프로젝트 경험으로 볼 때 다음과 같은 좋은 방법이 있습니다.
constants.js:
// constants.js
'use strict';
let constants = {
key1: "value1",
key2: "value2",
key3: {
subkey1: "subvalue1",
subkey2: "subvalue2"
}
};
module.exports =
Object.freeze(constants); // freeze prevents changes by users
main.js(또는 app.js 등)에서는 다음과 같이 사용합니다.
// main.js
let constants = require('./constants');
console.log(constants.key1);
console.dir(constants.key3);
도미닉이 제안한 해결책이 최선이라고 생각했지만, 여전히 "항상" 선언의 한 가지 특징을 놓치고 있습니다."const" 키워드를 사용하여 JS에서 상수를 선언하면 상수의 존재는 실행 시간이 아닌 해석 시간에 확인됩니다.따라서 코드 뒷부분에서 상수 이름을 잘못 입력한 경우 node.js 프로그램을 시작하려고 할 때 오류가 발생합니다.철자가 틀린 게 훨씬 낫지
Domino가 제안하는 바와 같이 define() 함수로 상수를 정의하면 상수의 철자를 잘못 입력해도 오류가 발생하지 않으며, 철자가 틀린 상수의 값은 정의되지 않습니다(이 때문에 디버깅의 문제가 발생할 수 있습니다).
하지만 이게 우리가 얻을 수 있는 최선인 것 같아.
또한 Constans.js에서는 Domino의 기능이 다음과 같이 개선되었습니다.
global.define = function ( name, value, exportsObject )
{
if ( !exportsObject )
{
if ( exports.exportsObject )
exportsObject = exports.exportsObject;
else
exportsObject = exports;
}
Object.defineProperty( exportsObject, name, {
'value': value,
'enumerable': true,
'writable': false,
});
}
exports.exportObject = null;
이렇게 하면 다른 모듈에서 define() 함수를 사용할 수 있습니다.이것에 의해, constant.js 모듈내의 상수와 함수를 호출한 모듈내의 상수를 정의할 수 있습니다.다음으로 모듈 상수를 선언하는 방법은 두 가지가 있습니다(script.js).
첫 번째:
require( './constants.js' );
define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js
define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module
두 번째:
constants = require( './constants.js' );
// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js
또한 define() 함수를 (글로벌오브젝트를 부풀리지 않고) 상수 모듈에서만 호출하는 경우 constants.js에서 다음과 같이 정의합니다.
exports.define = function ( name, value, exportsObject )
스크립트에서는 다음과 같이 사용합니다.
constants.define( 'SOME_CONSTANT', "const value 1" );
import
★★★★★★★★★★★★★★★★★」export
것이 합니다.) (2018년 기준)
types.displays(유형).
export const BLUE = 'BLUE'
export const RED = 'RED'
myApp.js
import * as types from './types.js'
const MyApp = () => {
let colour = types.RED
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
는 ★★★★★★★★★★★★★★★★★★★★★★★★」const
이 전원장치를 찾는 대부분의 사람들이 문제를 해결합니다.만약 당신이 정말 불변의 상수가 필요하다면, 다른 답을 찾아보세요.모든 것을 정리하기 위해 모든 상수를 폴더에 저장한 다음 폴더 전체를 요구합니다.
src/main.filename 파일
const constants = require("./consts_folder");
src/consts_folder/index.displays
const deal = require("./deal.js")
const note = require("./note.js")
module.exports = {
deal,
note
}
P. 여기서deal
★★★★★★★★★★★★★★★★★」note
입니다.
src/consts_folder/note.module
exports.obj = {
type: "object",
description: "I'm a note object"
}
obj
입니다.
src/consts_folder/folder.displays
exports.str = "I'm a deal string"
str
입니다.
main.js 파일의 최종 결과:
console.log(constants.deal);
출력:
{ deal: { str: '나는 거래 문자열이다'},
console.log(constants.note);
출력:
메모: { obj: { type: 'object', 설명: 'I\'''note object' }
또는 로컬 개체에서 "정수" 값을 그룹화하고 이 개체의 얕은 복제본을 반환하는 함수를 내보낼 수 있습니다.
var constants = { FOO: "foo" }
module.exports = function() {
return Object.assign({}, constants)
}
그러면 FOO를 재할당해도 상관없습니다. 왜냐하면 FOO는 로컬 복사본에만 영향을 주기 때문입니다.
Node.js는 Common을 사용하고 있기 때문에JS 패턴, 모듈 간에 변수를 공유할 수 있는 것은module.exports
또는 브라우저에서처럼 글로벌 var를 설정해서 사용할 수도 있지만, 창을 사용하는 대신global.your_var = value;
.
이 작업은 상수 자체가 아니라 익명 getter 함수를 사용하여 frozen 객체를 내보내는 방식으로 수행되었습니다.이것에 의해, 오타가 발생했을 경우에 런타임 에러가 발생하므로, const 이름의 단순한 오타로 인한 불량한 버그 발생의 리스크를 경감할 수고를 덜 수고를 덜 수 있습니다.다음은 ES6 기호를 상수로 사용하여 고유성을 보장하고 ES6 화살표 함수를 사용하는 전체 예입니다.이 접근법에 문제가 있는 것 같으면 피드백을 주시면 감사하겠습니다.
'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');
module.exports = Object.freeze({
getDirectory: () => DIRECTORY,
getSheet: () => SHEET,
getComposer: () => COMPOSER
});
웹 팩을 사용하는 것을 권장합니다(웹 팩을 사용하는 것으로 가정).
상수를 정의하는 것은 웹 팩 설정 파일을 설정하는 것만으로 간단합니다.
var webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'APP_ENV': '"dev"',
'process.env': {
'NODE_ENV': '"development"'
}
})
],
};
이러한 방법으로 소스 외부에서 정의하면 모든 파일에서 사용할 수 있습니다.
모듈에서 GLOBAL 영역을 침범하는 것은 좋은 방법은 아니지만, 구현이 절대적으로 필요한 시나리오에서는 다음과 같습니다.
Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});
이 자원의 영향을 고려해야 합니다.이러한 상수에 적절한 이름을 붙이지 않으면 이미 정의된 글로벌 변수를 덮어쓸 위험이 있습니다.
언급URL : https://stackoverflow.com/questions/8595509/how-do-you-share-constants-in-nodejs-modules
'programing' 카테고리의 다른 글
이름이 없는 로더 'app' 모듈에 있으므로 클래스에 캐스팅할 수 없습니다. (0) | 2023.01.27 |
---|---|
JSON 구문 분석 중 "예기치 않은 토큰 o" 오류가 발생했습니다. (0) | 2023.01.27 |
이클립스로 어떻게 돌아가? (0) | 2023.01.27 |
Vue 컴포넌트의 맵을 동적으로 갱신할 필요가 있다 (0) | 2023.01.27 |
Laravel 웅변가:조인된 테이블에서 특정 열만 가져오는 방법 (0) | 2023.01.17 |