简体   繁体   中英

How to import an external library into a ReactJS Application (Locally)

I've a ReactJS application, and I'm using MaterializeCSS through react-materialize. I've installed react-materialized and added the references to MaterializeCSS files in my index.html file, as ordered:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
(...)
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

It's working fine, but I will spend 10 days in a place with no internet, and I'd like to develop my project there, so the CDN hosted file won't work. So I'm trying to host materialize files in my own project.

I've managed to do that with css files, copied it to a folder in my project structure and imported in App.js:

import './resources/materialize/css/materialize.css';

But when I tried to do the same with .js file, I get tons of errors, since it's trying to transpile materialize.js files.

Where should I put this file and how can I reference it from my project?

You can install it via npm using windows command prompt, simply Start > Run > cmd, locate your project folder via cd <foldername> and type this:

npm install --save materialize-css@next

and at your Index.js : - which is in the root folder of your application

import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';

I also strongly recommend material UI which is very convenient with react applications: https://material-ui.com/

you can run

npm install --save materialize-css@next

and then you can add it in the index.js file the following import:

import 'materialize-css'; //This adds the Js file
import 'materialize-css/dist/css/materialize.min.css';

A simpler solution, to avoid potentially complex webpack setups is to temporarly download the actual files from their website:

https://materializecss.com/getting-started.html

And just place their file in your js folder and reference it via script tag, exactly as they show in their "Setup - Project Structure" section.

I know it's not the most elegant solution but it might work if you are in a rush, otherwise you need to look how to include the project with webpack without it touching its code.

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