简体   繁体   中英

Is it possible to import and use a react-redux component from vanilla javascript

I have two applications, one of them is written in vanilla javascript with html and css. The other one is a react + redux application.

Is it possible to import and use the components from my react + redux application inside my vanilla javascript application without introducing a dependency on react and redux?

Short answer, yes , depending how you've written the code. Namely, assuming you are using ES6 Modules, or using a transpiler that will handle them as such.

Firstly, remember that react-redux is just an implementation of redux for react. Redux works fine by itself.

Assuming what you are talking about is reusing your reducers and action creators, then that will be fine - as all they are are pure functions.

For example say your app looks like:

index.js

import React from "react"; 
import store from "./store";
import {createUser} from "./actions"; 
import { Provider } from 'react-redux';

//etc. 

store.js

import { createStore } from 'redux'
import rootReducer from '../reducers'

    export default function() {
        return createStore(rootReducer); 
    }

actions.js

   export  function addUser(name) {
       return {
            type: "ADD_USER", 
            payload: name, 
       }
   }

reducers.js

   export default function (state ={}, action)  {

        return {
            value: action.payload
        }
    }

In this scenario, lets say you want to reuse the action, and the reducer.

Then you can just import the functions from these modules. ESM modules are smart enough to just import what they need.

On the otherhand, say you were importing the createStore (default) method, then you would also be importing the dependency on redux.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM