最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Modifying an imported variable causes 'Assignment to constant variable' even if it is not a constan

programmeradmin3浏览0评论

I have two files, file1 exports a variable 'not a constant' var x=1 and file2 which imports this variable from it

the problem is that I canno't modify that imported variable even it is not a constant!

file1.js

export var x=1 //it is defined as a variable not a constant

file2.js

import {x} from 'file1.js'
console.log(x) //1
x=2 //Error: Assignment to constant variable

I have two files, file1 exports a variable 'not a constant' var x=1 and file2 which imports this variable from it

the problem is that I canno't modify that imported variable even it is not a constant!

file1.js

export var x=1 //it is defined as a variable not a constant

file2.js

import {x} from 'file1.js'
console.log(x) //1
x=2 //Error: Assignment to constant variable
Share Improve this question edited Aug 15, 2024 at 22:37 Cody Gray 245k53 gold badges504 silver badges584 bronze badges asked Dec 11, 2018 at 11:30 xx yyxx yy 6141 gold badge8 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

That's an effect of the immutable exported module values. You can override that with another function in the same module

In your file 1 :

export let x = 1;
export function modifyX( value ) { x = value; }

In your file 2

import { x, modifyX } from "file1.js"

console.log( x ) // 1;
modifyX( 2 );
console.log( x ) // 2;

you can try to set the x as an object property like this:

export default {
    x: 1
}

then from your second file:

import file1API from "./file1.js";

console.log(file1API.x); //1
file1API.x = 2;
console.log(file1API.x); //2

note that the value of x will also be updated in "file1.js".

发布评论

评论列表(0)

  1. 暂无评论