본문 바로가기
JavaScript/JavaScript with Error

[해결 방법] SyntaxError: Cannot use import statement outside a module

by HJ0216 2023. 6. 6.

🟨 기본 환경: IDE: VS code, Language: JavaScript

 

 

발생 Error

CMD에서 node productSlice.js로 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import {createSlice} from '@reduxjs/toolkit';
// createSlice: reducer 생성, 매개변수-객체
 
let initialState = {
    productList: [],
    selectedItem: null,
};
 
// name: unique한 action name을 만드는데 쓰이는 prefix
// initialState: reducer state
// reducers: state, action을 매개변수로 받는 함수 생성
const productSlice = createSlice({
    name'product',
    initialState,
    reducers: {
        getAllProduct(state, action) {
            state.productList= action.payload.data
            // initialState의 productList을 action의 payload.data로 변경
        },
        getSingleProduct(state, action) {
            state.selectedItem = action.payload.data
        },
    }
});
 
console.log('ppp', productSlice);
 
export default productSlice.reducer;
// productSlice: reducers가 담긴 reducer 반환
 
 
 

🚨 다음과 같은 Error 발생

SyntaxError: Cannot use import statement outside a module

 

 

발생 원인

Node.js에서 파일에서 import 문을 사용하려고 했을 때 발생

 

 

해결 방법

Node.js에서는 import 대신 require 문을 사용하여 모듈을 가져와야 함

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const { createSlice } = require('@reduxjs/toolkit');
// createSlice: reducer 생성, 매개변수-객체
 
let initialState = {
    productList: [],
    selectedItem: null,
};
 
// name: unique한 action name을 만드는데 쓰이는 prefix
// initialState: reducer state
// reducers: state, action을 매개변수로 받는 함수 생성
const productSlice = createSlice({
    name'product',
    initialState,
    reducers: {
        getAllProduct(state, action) {
            state.productList= action.payload.data
            // initialState의 productList을 action의 payload.data로 변경
        },
        getSingleProduct(state, action) {
            state.selectedItem = action.payload.data
        },
    }
});
 
console.log('ppp', productSlice);
 
export default productSlice.reducer;
// productSlice: reducers가 담긴 reducer 반환