Reputation: 852
I am not very familiar with javascript modules. I am starting to work on a project and for that I needed a library from npm.
https://www.npmjs.com/package/random-color-pair
Therefore, as I ran npm i random-color-pair
This made a "node modules" named folder which contained the files of the package. I tried several ways to import that in my javascript but am not able to find a way to do so.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="main.js" type="module">
</script>
</body>
</html>
I have already tried the following (none of them work):
import getColorPair from "random-color-pair";
import getColorPair from "node_modules/random-color-pair";
import getColorPair from "./node_modules/random-color-pair";
import "./node_modules/random-color-pair";
import getColorPair from "./node_modules/random-color-pair/index";
import "./node_modules/random-color-pair/index";
Upvotes: 0
Views: 3362
Reputation: 828
This won't work right off the bat, you will need a bundler like webpack or parcel to compile/combine the code in the package with your code. I'll show you how to use and configure parcel because that is the easiest.
Start by installing the bundler:
npm install parcel-bundler -D
Update the scripts
section in the package.json
{
"scripts": {
"dev": "parcel ./index.html",
"build": "parcel build ./index.html"
}
}
Now you can install any module from npm:
npm i <module_name>
And import it in your main.js
file like so:
import module_name as 'module_name';
To start up your dev server(which will automatically change when you update your code) run this:
npm run dev
And for the production bundle(which can be uploaded to hosting platforms):
npm run build
I hope this was useful and let me know if it worked for you!
Upvotes: 3
Reputation: 2747
random-color-pair
internally use this library : randomcolor.
You should install this directly like like this : npm i randomcolor
And import it like this :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="node_modules/randomcolor/randomColor.js"></script>
<script src="main.js"></script>
</body>
</html>
function getColorPair() {
const isForegroundDark = Math.random() < 0.5
const foregroundColor = randomColor({
luminosity: isForegroundDark ? 'dark' : 'light'
})
const backgroundColor = randomColor({
luminosity: isForegroundDark ? 'light' : 'dark'
})
return [foregroundColor, backgroundColor]
}
var color = getColorPair();
console.log("color", color);
Do not need to import anything in JS file.
Upvotes: 1