How to import a js package in Angular 2 project? - javascript

I have an Angular 2 project and I would like to add a JavaScript package called bootstrap-slider and I have trouble understanding how I am supposed integrated the package in the project.
I started by adding the package to my node_modules by adding "bootstrap-slider" under dependencies in the package.json file and running "npm install". The entry in my package looks like this:
"bootstrap-slider": "^9.2.0",
I can see that a new folder with content for the slider has been added inside of node_modules. After looking up several guides and explanations I have tried the following in my index.html in order to properly import and use the JS package. My index html now looks 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">
<title><%= webpackConfig.metadata.title %></title>
<meta name="description" content="<%= webpackConfig.metadata.description %>">
<% if (webpackConfig.htmlElements.headTags) { %>
<!-- Configured Head Tags -->
<%= webpackConfig.htmlElements.headTags %>
<% } %>
<!-- base url -->
<base href="<%= webpackConfig.metadata.baseUrl %>">
<script src="../node_modules/bootstrap-slider/src/js/bootstrap-slider.js"></script>
<script>
System.config({
paths: {
bootstrap-slider: ‘../node_modules/bootstrap-slider/src/js/bootstrap-slider.js’
}
});
</script>
</head>
<body>
<app>
</app>
<div id="preloader">
<div></div>
</div>
<% if (webpackConfig.metadata.isDevServer && webpackConfig.metadata.HMR !== true) { %>
<!-- Webpack Dev Server reload -->
<script src="/webpack-dev-server.js"></script>
<% } %>
<link
href='https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900italic,900&subset=latin,greek,greek-ext,vietnamese,cyrillic-ext,latin-ext,cyrillic'
rel='stylesheet' type='text/css'>
</body>
</html>
I have then tried running the example code (wihtout jQuery) on their github in one of the pages on my website to no end.
<input
type="text"
name="somename"
data-provide="slider"
data-slider-ticks="[1, 2, 3]"
data-slider-ticks-labels='["short", "medium", "long"]'
data-slider-min="1"
data-slider-max="3"
data-slider-step="1"
data-slider-value="3"
data-slider-tooltip="hide"
>
I would like to know is how to add this JavaScript package and other packages in the future to my project. Any help is greatly appreciated!

I think it is more comfortable to keep a single package manager for your projects. If still you prefer using a specific package manager for your front-end runtime dependencies, I do not recommend using bower anymore, as it is getting deprecated. Use Yarn instead.
It is perfectly possible to include styles and scripts from node_modules if you are using angular-cli to set your project up. You can edit the .angular-cli.json file in your project and add as many styles or scripts to your angular application as necessary. In order to add styles and scripts you may add them to the app.styles and app.scripts arrays respectively:
{
...
"apps": [
{
...
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": ["../node_modules/bootstrap/dist/js/bootstrap.min.js"],
}
]
}
Angular-cli will include the styles and scripts you specify in .angular-cli.json inside the styles.bundle.js and scripts.bundle.js respectively. Both bundles will be automatically added to your Angular application for you.

I've never used bootstrap-slider, but already install many modules. Have you any error message in your Javascript console ?
Otherwise, to add module you have to do the following :
install it via npm or bower (like you have done or by execute : npm install bootstrap-slider )
import JS and CSS files in your index.html file (again, you have already done that)
import module in your module config, app.js, here is an exemple with ngRoute module :
angular
.module('myApp', [
'ngRoute'
]);

Related

Vuejs loading CSS and JS files giving MIME type error

I have created a new vue-webpack project. when I want to add CSS and js files through link and script it gives me this error The stylesheet http://localhost:8080/src/assets/styles.css was not loaded because its MIME type, “text/html”, is not “text/css”.
and for js files, it gives this error Uncaught SyntaxError: expected expression, got '<'
I have included them inside index.html file.
I used to work like this, but now at this time, I am facing this.
css file:
body {background:black;}
js file:
console.log('hello world')
index.html:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>myapp</title>
<link rel="stylesheet" href="./src/assets/styles.css">
</head>
<body>
<div id="app"></div>
<script src="./src/assets/form.js"></script>
</body>
</html>
First, I strongly suggest you stop using the old Vue CLI v2 and update to the latest version
npm install -g #vue/cli
If you want to include some extra JS, CSS or other files that are not part of the Webpack bundle, you need to move them into the public folder
- public
- index.html
- favicon.ico
- form.js
- styles.css
and reference them like this
<link rel="stylesheet" href="<%= BASE_URL %>styles.css">
<script src="<%= BASE_URL %>form.js"></script>
See https://cli.vuejs.org/guide/html-and-static-assets.html
Importing the assets from main.js solved the problem.

How does a Vue app get launched if the index.html doesn't load any javascript?

None of the resources I've read about Vue attempt to explain how a Vue application is launched.
There are three files involved: public/index.html, src/main.js, and src/App.vue. A scaffold created with vue cli 4.1.1 contains this index.html which apparently is the entry point:
<!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">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>sample-vue-project</title>
</head>
<body>
<noscript>
<strong>We're sorry but sample-vue-project doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
The main.js file creates the Vue App itself, but the index.html doesn't load main.js. If I double click on index.html I get a blank page, so something else has to intervene to launch the App. The comment in index.html says that files will be auto injected, but what does that injection?
Is the Vue launch process documented somewhere?
The Vue Cli handles the injection when you are developing locally as your run command will be something like npm run serve for default configurations.
When you get round to putting the code into production you'll end up running a different command npm run build which will create a new set of files where the index.html file will include a script tag that references all your javascript code. Under the hood it uses webpack to do all the asset linking.
See the Vue Cli website for more details.

Don't understand project structure of Vue project created with vue-cli

I am new to Vue.js and have never used a frontend framework before.
I created a project using the "vue create" command with the usual plugins and everything (nothing game changing), and everything worked fine.
I wanted to start from 0, so I removed everything but the index.html file in the public directory, the main.js file in the src directory and the configuration files(see below).
Now when I load the page you can see "Test" and "{{message}}" for an instant and then it disappears leaving the page completely blank.
So my question is, how is the main.js file connected to the index.html file. I know from webpack that you need an entry point and link everything from there, but i cannot find such thing here, as main.js doesn't include index.html. So why doesn't my code work as intended? I want it to say Hello World.
index.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" />
<link rel="icon" href="<%= BASE_URL %>favicon.ico" />
<title>Vue Getting Started</title>
</head>
<body>
<noscript>
<strong>
We're sorry but vue_getting_started doesn't work properly without
JavaScript enabled. Please enable it to continue.
</strong>
</noscript>
<div id="app">
<h1>Test</h1>
<h1>{{ message }}</h1>
</div>
<!-- built files will be auto injected -->
</body>
</html>
main.js
import Vue from 'vue'
const app = new Vue({
el: '#app',
data: {
message: 'Hello World!'
}
})
Where you see the line
<!-- built files will be auto injected -->
is where webpack will inject a script tag that loads the bundled javascript, you should be able to see that when you use the devtools. This is where your main entry chunk is being loaded. However, this only happens if webpack is actually doing its job either by running the dev server or by creating a production bundle.
If by "when I load the page" you mean opening up the index.html file in your browser, this won't do much. You will need to run webpack, in the newer versions of the vue cli you can do that by navigating to the root folder and running vue-cli-service serve

React boilerplate doesn't load js files in the index.html

I'm testing React-boilerplate and I'm trying to load some javascript files in the app/index.html file:
<!doctype html>
<html lang="en">
<head>
<!-- The first thing in any HTML file should be the charset -->
<meta charset="utf-8">
<!-- Make the page mobile compatible -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Allow installing the app to the homescreen -->
<link rel="manifest" href="manifest.json">
<meta name="mobile-web-app-capable" content="yes">
<script type="text/javascript" src="myJScriptFile1.js"></script>
<script type="text/javascript" src="myJScriptFile2.js"></script>
</head>
<body>
<!-- Display a message if JS has been disabled on the browser. -->
<noscript>If you're seeing this message, that means <strong>JavaScript has been disabled on your browser</strong>, please <strong>enable JS</strong> to make this app work.</noscript>
<!-- The app hooks into this div -->
<div id="app"></div>
<!-- A lot of magic happens in this file. HtmlWebpackPlugin automatically includes all assets (e.g. bundle.js, main.css) with the correct HTML tags, which is why they are missing in this HTML file. Don't add any assets here! (Check out webpackconfig.js if you want to know more) -->
</body>
</html>
This is the default index.html file. I'm running it with npm or yarn and the server console shows me no error, but my browser console keeps telling me:
Uncaught SyntaxError: Unexpected token <
Just like this, there is no more error. These javascript files work fine because I'm using them into another React based project, and I'm calling them into the index.html file as well. The console prints that error per file. If I trace the error it leads me to the correspond .js file.
After almost a week searching the web I couldn't find a solution. So that's it, does anybody have any idea on how to solve this?
Well, I'm answering myself. I needed a little bit more of research in webpack. I achieve this through webpack:
installed npm i add-asset-html-webpack-plugin -D
then, in the webpack config file, under plugins I added:
new AddAssetHtmlPlugin({ filepath: require.resolve('./some-file') })
and that's it.

How to install Twitter Bootstrap to an angular 2 project?

I have cloned the angular 2 seed project that provides fast, reliable and extensible starter for the development of my Angular 2 project.
Now, I want to install Twitter Bootstrap into my project. I followed the Angular docs:
Let's add the stylesheet.
Open a terminal window in the application root folder and enter the command:
npm install bootstrap --save
Open index.html and add the following link to the .
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
But Twitter Bootstrap classes are not working in my html files. And When I checked the source code from my browser, I found that my index.html file does not contain this line of code
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"> even though I have added it to my index. I have tried to refresh the browser several times and I have searched for a configurable way to install Twitter Bootstrap to my project but nothing found.
Here is my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<base href="<%= APP_BASE %>">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><%= APP_TITLE %></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- inject:css -->
<link rel="stylesheet" href="../../node_modules/bootstrap/dist/css/bootstrap.min.css">
<!-- endinject -->
</head>
<body>
<vynd-web-user-app>Loading...</vynd-web-user-app>
<script>
// Fixes undefined module function in SystemJS bundle
function module() {}
</script>
<!-- shims:js -->
<!-- endinject -->
<% if (ENV === 'dev') { %>
<script>
System.config(<%=
JSON.stringify(SYSTEM_CONFIG, null, 2)
%>)
</script>
<% } %>
<!-- libs:js -->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>-->
<!-- endinject -->
<!-- inject:js -->
<!-- endinject -->
<% if (ENV === 'dev') { %>
<script>
System.import('<%= BOOTSTRAP_MODULE %>')
.catch(function (e) {
console.error(e,
'Report this error at https://github.com/mgechev/angular2-seed/issues');
});
</script>
<% } %>
</body>
</html>
And here is an overview of my project structure:
And here is the loaded index.html file in my browser:
The problem is in this part of code
<!-- inject:css -->
<link rel="stylesheet" href="../../node_modules/bootstrap/dist/css/bootstrap.min.css">
<!-- endinject -->
First, when I saw the <!-- inject:css --> and <!-- endinject --> comments in my index.html file, I thought that the team who are creating the angular 2 seed project provides those comments for us for more readable code and It is preferred to add every new css library between those two comments. But when I added the twitter bootstrap framework outside those two comments, it worked very well. Maybe every line of code that resides between the <!-- inject:css --> and <!-- endinject --> would be overridden by some automatically injected codes by some angular configuration files.
If you use angular-cli for your project my answer could be useful for you.
in root project directory run npm install --save bootstrap
edit .angular-cli.json - the file is in same location. Find here "styles" section
And add your bootstrap.css:
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
I've added "../node_modules/bootstrap/dist/css/bootstrap.min.css", in my project. And now I can use all bootstrap classes.
P.S.
If you need not only bootstrap styles but some bootstrap scripts, just add into .angular-cli.json also script location in correspond section:
"scripts": [
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
The route where you are loading the .css should be css/bootstrap/bootstrap.min.cs
Keep in mind that if you put ../ in your index.html, it will try to look in the parent folder where that file is, and since your css is in a folder in the same folder where you currently have the index.html try that.
Hope this helps

Categories

Resources