grunt bowerInstall not working - angularjs

I'm setting up a new AngularJS project (first time for me) and I'm finding it very touchy... Latest issue is getting bower to properly configure things in my index.html file.
If I just hardcode things to the googleapis, it all works just fine (example in the index.html file).
If I setup bower and do a grunt bowerInstall, it adds what look to be the correct lines in my index.html but they don't work at all. I get errors like:
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8081/bower_components/angular/angular.js".
and
Uncaught SyntaxError: Unexpected token < for the angular files.
So far bower has been a royal pain... any ideas what's going wrong here? Thanks!
BTW, the simple app is working as expected and I've gotten some basic karma tests working.
bower.json:
{
"name": "meanjs_book",
"version": "0.1.0",
"homepage": "https://github.com/JESii/xxx",
"authors": [
"Jon Seidel <jseidel#edpci.com>"
],
"description": "Rudimentary app from MeanJS Book",
"main": "server.js",
"moduleType": [
"node"
],
"keywords": [
"MongoDB",
"Express",
"AngularJS",
"Node",
"HighPlans"
],
"license": "MIT",
"private": true,
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests",
"spec"
],
"dependencies": {
"angular-route": "~1.3.15",
"angular": "~1.3.15",
"angular-animate": "~1.3.15",
"angular-mocks": "~1.3.15"
}
}
Gruntfile
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
},
bowerInstall: {
target: {
// Point to the files that should be updated when
// you run `grunt bowerInstall`
src: ['public/app/views/index.html'], // index.html support
// Optional:
// ---------
cwd: '',
dependencies: true,
devDependencies: false,
exclude: [],
fileTypes: {},
ignorePath: '',
overrides: {}
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['uglify']);
grunt.loadNpmTasks('grunt-bower-install');
};
index.html:
<!-- AngularJS -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" type="text/javascript" charset="utf-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js" type="text/javascript" charset="utf-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.js" type="text/javascript" charset="utf-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-mocks.js" type="text/javascript" charset="utf-8"></script>
<!-- bower:js -->
<!-- <script src="../../../bower_components/angular/angular.js" type="text/javascript"></script> -->
<!-- <script src="../../../bower_components/angular-route/angular-route.js" type="text/javascript"></script> -->
<!-- <script src="../../../bower_components/angular-animate/angular-animate.js" type="text/javascript"></script> -->
</script> -->

I'm assuming you're getting that error when running grunt serve. The console message you pasted indicates that grunt isn't allowing JS files through. If a particular file type isn't allowed, it's replaced with index.html which is why it was transferred with MIME type HTML. Where did you get that Gruntfile from?
Additionally, I recommend using Yeoman to scaffold a basic Angular app. Check it out here: http://yeoman.io/codelab.html. It's very easy to follow and will make you more comfortable with using tools like Grunt & Bower.

Related

How to embed React App into another website

I have an old website running on server x. Now a React-App has been developed, which is on server y.
The website should display the React-App.
I have searched and read several posts on the topic but with no success so far.
The only solution currently working is an iframe but we don't want this.
If I do
npm run
and inspect the source on the server hosting the React-App, there is the following:
...
<div id="react-reporting"></div>
<script src="/static/js/bundle.js"></script><script src="/static/js/0.chunk.js"></script><script src="/static/js/main.chunk.js"></script>
Basically I would like to take this HTML-part and put it into the old site. Is this possible and if yes how?
My approach actually works, but I missed these two scripts:
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
So for testing locally it is:
<div id="react-reporting"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="http://localhost:3000/static/js/bundle.js"></script><script src="http://localhost:3000/static/js/0.chunk.js"></script>
<script src="http://localhost:3000/static/js/main.chunk.js"></script>
I also approached an error regarding sockjs which was caused by the test-file, which imports the React App, was being opened as file:// not via http://
Edit
After some more tests, I found using webpack is the best solution - it makes the app accessible as a single file.
package.json
...
"scripts": {
"start": "webpack-dev-server --inline --hot",
"build": "webpack --config webpack.config.js"
},
...
webpack.config.js
const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")
module.exports = {
entry: ['#babel/polyfill','./src/index.js'],
output: {
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
],
},
optimization: {
minimizer: [new UglifyJsPlugin()]
}
}
polyfill is needed for compatibility with IE11
every file processed (starting with the entries) counts as module. If it matches the "test"-part of a rule, the rule is applied (except for the excludes).
.babelrc
{
"presets": ['#babel/react',
['#babel/preset-env', {
"targets": {
"browsers": ["last 2 versions", "ie >= 11"]
}
}]],
"plugins": ['#babel/plugin-proposal-class-properties']
}
plugin-proposal-class-properties is only needed because I have some static members in classes.
When running
npm start
the Webpack-Dev-Server will start and make the app accessible under http://localhost:8080/dist/bundle.js.
Code to embed the app in another site:
<div id="react-reporting"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="http://localhost:8080/dist/bundle.js"></script>
If you are using create-react-app, go to the folder of your React App, and insert this command:
npm run build
This will generate a ./build folder with all that you need for your app.
Then it's simply a matter of dragging the ./build folder to server x.
You can also change the HTML that calls the react app so it will fit the old webpage.

Bootstrap.css not getting added to index.html in dist

I have a grunt task configured (I am working existing project). I am not sure where to find particular task. I have an "index.html" file getting created and added to the "dist" folder after every compile and build. But in the index.html i manually have to add the following every time:
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css">
and also the -
<base href="/">
For AJS.
What might be the possible issue?
I don't want to edit bower.json instead do it using grunt task. so how do i do it?
I have the following:
var buildConfig = module.exports = {
// Wiredep options
wiredepOptions: {
//
// devDependencies: true, // <-- injects bower devDependencies
//
// exclude: [ // <-- List of patterns to exclude
//
// /bootstrap\.js/
// ]
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.css"
]
}
},
This gives me error. how do i resolve it?
This is because the main object in Bootstrap's bower.json mention a reference to the less file not the css
"main": [
"less/bootstrap.less",
"dist/js/bootstrap.js"
],
Wiredep is the grunt task that is responsible for injecting those assets so it have no idea where the CSS file is. You can do it by providing an override in wiredep task in your gruntfile.js as follow:
wiredep: {
...,
overrides: {
'bootstrap': {
'main': [
'dist/js/bootstrap.js',
'dist/css/bootstrap.css' // Note this
]
}
}
}
},
Running grunt wiredep again will inject the CSS file to your HTML as expected.
Note: This won't work unless your HTML have this HTML comment
<!-- bower:css -->
The styles will be injected here
<!-- endbower -->
I could not resolve it with editing Gruntfile but added this in bower.json :
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.css"
]
}

Grunt usemin and absolute (nonexistent) file paths

My directory structure looks like this, I have an absolute path /static mapped to my public dir
+public/
+--app/
+--dist/
|--Gruntfile.js
|..
|..
Currently, everything builds fine and I wind up with my minified/rev'd files in dist but the index.html file contains relative paths like:
<script src="some-file.56a75bad.js"></script>
When I need them to be:
<script src="/static/dist/some-file.56a75bad.js"></script>
Can't seem to figure out how to achieve this, everything I've tried winds up giving my the right file paths but not the rev'd file, i.e:
<script src="/static/dist/some-file.js"></script>
My solution: copy task moves all scripts to a .tmp folder. uglify task then runs and outputs to a folder hierarchy in .tmp that the absolute paths to resolve to. After those 2 tasks are run I have a folder structure that looks like this (mid build):
public/
+--.tmp/
+--static/
+--dist/
|--application.min.js
|--dependencies.min.js
+--app/
+--bower_components/
+--dist/
|--Gruntfile.js
|--index.html
A little piece of my index.html
<!-- build:js /static/dist/dependencies.min.js -->
<script src="/static/dist/dependencies.min.js"></script>
<!-- endbuild -->
<!-- build:js /static/dist/application.min.js -->
<script src="/static/dist/application.min.js"></script>
<!-- endbuild -->
Now it's business as usual, the useminPrepare filerev and usemin tasks are run.
And my GruntFile:
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.config.init({
useminPrepare: {
html: 'dist/index.html',
options: {
dest: './dist'
}
},
usemin:{
html:['dist/index.html'],
options: {
assetsDirs: ['.tmp']
}
},
copy:{
html: {
src: './index.html',
dest: 'dist/index.html'
},
javascripts: {
cwd: '',
src: 'app/scripts/**',
dest: '.tmp',
expand: true
}
},
uglify: {
build: {
options: {
mangle: true
},
files: {
'.tmp/static/dist/application.min.js': ['.tmp/app/**/*.js'],
'.tmp/static/dist/dependencies.min.js': [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js'
// All my other 3rd party libs, I realized this can be done in index.html but there's environmental constraints making that not possible
]
}
}
},
filerev: {
dist: {
src: ['.tmp/static/dist/application.min.js', '.tmp/static/dist/dependencies.min.js'],
dest: 'dist'
}
}
});
grunt.registerTask('build',[
'copy:javascripts',
'copy:html',
'uglify',
'useminPrepare',
'filerev',
'usemin'
]);
};

grunt task to modify yeoman angular index.html

yo angular sets up a basic scaffold for writing angular apps. So in index.html we have code as follows:
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.css" />
<!-- endbower -->
<!-- endbuild -->
I am looking for a task that would remove those lines and inject the correct location of the files. For e.g.:
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/bootstrap-theme.css" />
Or is there some alternate way to deal with this...like for e.g. have the watch task create different versions of index.html, say index.html.fooTarget; it gets updated with the correct paths for that target; and then when it comes to the grunt task have the latter file copied appropriately.
What can be done to deal with this?
Maybe you should let the paths be as they are since CSS files are bower dependencies, too. Copy the dependencies to a directory with the same relative path?
But if you will, I think this will help you modify your grunt tasks.
I assume you have (at least) the following in your package.json.
{
"name": "app",
"version": "0.0.1",
"dependencies": {},
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-copy": "~0.4.1",
"grunt-text-replace": "0.3.11"
}
}
Then the minimal copy & replace tasks could look like the following in your Gruntfile.js (you can combine copy and replace by using grunt-contrib-copy alone, if you will).
'use strict';
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-text-replace');
grunt.initConfig({
src: 'src',
dest: 'dest',
copy: {
dev: {
expand: true,
cwd: '<%= src %>',
src: '{,*/}*.html',
dest: '<%= dest %>/'
}
},
replace: {
dev: {
src: ['<%= dest %>/{,*/}*.html'],
overwrite: true,
replacements: [{
from: 'bower_components/bootstrap/dist/css',
to: 'css'
}]
}
}
});
grunt.registerTask('prepare', function(val) {
var target = val || 'dev';
grunt.task.run([
'copy:' + target,
'replace:' + target
]);
});
};
Now when you run prepare task with desired target it will copy all HTML files from src to dest directory and have desired CSS paths replaced, leaving original files intact.
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
--> will be replaced as -->
<link rel="stylesheet" href="css/bootstrap.css" />

Angular and Grunt

I'm a Grunt newbie and I'm trying to convert an Angular app (based on angular-seed) to use it for CSS/JS concat/minification. I have an index.html file that defines the CSS and JS files:
<!-- build:css css/myjmh.css -->
<link rel="stylesheet" href="lib/bootstrap/bootstrap.min.css"/>
<link rel="stylesheet" href="lib/font-awesome/font-awesome.min.css"/>
<link rel="stylesheet" href="lib/toaster/toaster.css"/>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/custom.css"/>
<link rel="stylesheet" href="css/responsive.css"/>
<!-- endbuild -->
...
<!-- build:js js/myjmh.min.js -->
<script src="lib/jquery/jquery-1.10.2.min.js"></script>
<script src="lib/bootstrap/bootstrap.min.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-animate.min.js"></script>
<script src="lib/angular/angular-cookies.min.js"></script>
<script src="lib/angular/angular-resource.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/fastclick.min.js"></script>
<script src="lib/toaster/toaster.js"></script>
<script src="lib/webshim/modernizr.min.js"></script>
<script src="lib/webshim/polyfiller.min.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<!-- endbuild -->
I'm trying to use grunt-usemin and its useminPrepare task to grab these values from my HTML.
Here's my Gruntfile.js:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ["dist"],
copy: {
main: {
src: 'app/index.html',
dest: 'dist/index.html'
}
},
useminPrepare: {
html: 'app/index.html'
},
usemin: {
html: ['dist/index.html']
},
ngmin: {
dist: {
files: [
{
expand: true,
cwd: '.tmp/concat/js',
src: '*.js',
dest: '.tmp/concat/js'
}
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-ngmin');
grunt.loadNpmTasks('grunt-usemin');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', [
'copy', 'useminPrepare', 'concat', 'ngmin', 'uglify', 'cssmin', 'usemin'
]);
};
With all these settings, a "dist" directory is created with all the artifacts and everything seems to be generated/concatenated and minified correctly. However, when I load the new page up in my browser, I get the following error:
Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.2.3/$injector/unpr?p0=aProvider%20%3C-%20a
It seems like Grunt is doing something that doesn't play well with Angular. Any ideas on what this might be?
I was able to solve this by turning off mangling in uglify:
uglify: {
options: {
report: 'min',
mangle: false
}
}
As you might notice from my Gruntfile.js, ngmin is already used and this doesn't seem to help.
Found answer here: https://stackoverflow.com/a/17239358/65681
You need to do one of two things:
Make all of your angular code minification-friendly. See: http://docs.angularjs.org/guide/di#dependency-injection_dependency-annotation
Use a tool like grunt-ngannotate
If you are having same issues with declarations as I had, you could also use ng-annotate in order to achieve this. Here is a link to github: https://github.com/mzgol/grunt-ng-annotate
My working configuration is:
ngAnnotate: {
options: {
singleQuotes: true,
regexp: '^(ng\n?[\\ ]+(.*)|(module.*))$'
},
prod: {
files: [{
expand: true,
src: 'dist/**/*.js'
}]
}
}
Use it carefully as it will modify existing files. My assumption is that files in 'dist' folder should be generated by Grunt and can be deleted at any time.
As others have stated, it seems that you have a problem with minification. I see that you're using ngmin. But ngmin may not work when a file with mixed patterns is thrown at it. I mean, make sure that all of the files that you pass to ngmin don't already have minification-safe pattern.
Mangle false shouldn't be the solution, actually the code is not minification friendly, but the issues that I had were not explicitly described here, so they were:
1) "Make sure you only define each module with the angular.module(name, [requires]) syntax once across your entire project. Retrieve it for subsequent use with angular.module(name)" - I used it wrong in many places and it worked with mangle:false, breaking when setting mangle:true
2) I used bootstrap modal windows specifying instance controller not as a string, I've found the solution here

Resources