Full Stack Web Developer.
Syaku (샤쿠)

Java, JS (ES6+), Spring, Spring security, jQuery, Reactjs, Bootstrap.

        

07-12 08:23


Spring Boot 2 보기 Front-end 보기 DevOps 보기 Spring 3 보기 Spring Security 3 보기

React Dynamic Import : 동적 임포트

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;


댓글 남기기
◀ PREV 1234567···14 NEXT ▶