简体   繁体   中英

Where/how do I store functions that can be used in Vue front-end and Node back-end simultaneously?

I am just starting out with a Node/Express back-end and a Vue.js front-end. I am using server-side rendering as well.

I want to create some utility functions that format textual strings and then re-use those functions in both the front-end and the back-end. An example of such a function would be RemoveHTML() which takes HTML text and uses regex to remove all the tags leaving me with just bare text. I need to use this function all over my website - for example when reading data from a database and stripping the HTML before displaying it to the user.

I understand I can create a Vue mixin but that will only work for the front-end. I also want to run the RemoveHTML() function in Node.js if a user submits HTML code through a form and I need to remove HTML before storing it in the database (just an example not a real use case).

Where can I store my 'global' functions so that both Vue.js and Node.js can use them?

Store them in a .js file (or .ts?) accessible by both. You can create a plugin or mixin to wrap the functionality for Vue, but the business logic should be in separate js/ts files even for Vue project if possible.

I suspect you may be using two separate repos, one for back-end and one for front-end. In this case you may want to create a separate repo to sharing between projects easier. Even better, you can put this publish this code to npm (either make it publicly available to all or use subscription to keep private)

Alternatively you may also have a monorepo that stores back-end and front-end code in same git repo, so you can just keep shared code there too (with the unit tests).

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