React Dynamic Import : 동적 임포트
728x90
반응형
React Dynamic Import : 동적 임포트
리액트에서 동적 임포트를 사용하기 위한 소스 코드이다.
install
$ npm install babel-plugin-dynamic-import-webpack eslint-plugin-import eslint-import-resolver-webpack -D
or
$ yarn add babel-plugin-dynamic-import-webpack eslint-plugin-import eslint-import-resolver-webpack -D
webpack
webpack.config.js
resolve: {
alias: {
_root: path.resolve(__dirname, src),
},
},
eslint
.eslintrc
"settings": {
"import/resolver": "webpack",
"import/parser": "babel-eslint"
},
babel
.babelrc
"plugins": [
"dynamic-import-webpack",
]
Component
import React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
path: PropTypes.string.isRequired,
};
class DynamicImport extends React.Component {
constructor(props) {
super(props);
this.load = this.load.bind(this);
this.state = {
Component: null,
};
this.load(props.path);
}
componentWillReceiveProps(nextProps) {
this.load(nextProps.path);
}
load(path) {
import(`_root/${path}`).then((module) => {
this.setState({ Component: module.default });
});
}
render() {
const { Component } = this.state;
if (Component) return <Component {...this.props} />;
return null;
}
}
DynamicImport.propTypes = propTypes;
export default DynamicImport;
728x90
반응형
'Front-end > React' 카테고리의 다른 글
리액트 개발 환경 :: React Development Environment (0) | 2018.10.14 |
---|---|
JS Dragula autoScroll with React (0) | 2018.02.20 |
React component lifecycle : 리액트 컴포넌트 생명주기 (0) | 2017.11.18 |
React Validator : 폼 유효성 검증기 (0) | 2017.11.12 |