TemplateCache of NPM Modules not loading (AngularJS 1.X and Webpack) - angularjs

I created a angular 1.x project using fountain-angular yeoman generator with webpack for module management.
I then added angular-strap as a dependency to this project.
Now when i try to use angular-strap plugins like tabs or select in my application, am not able to get the corresponding template of these components loaded. Got the below console error.
Error: [$compile:tpload] Failed to load template: tab/tab.tpl.html (HTTP status: undefined undefined)
Am not sure if i have to change anything in webpack config file to get these templates loaded fine. Below is what my config looks like now.
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const autoprefixer = require('autoprefixer');
module.exports = {
module: {
rules: [
{
test: /\.json$/,
loaders: [
'json-loader'
]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
enforce: 'pre'
},
{
test: /\.(css|scss)$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
config: {
path: './postcss.config.js'
},
plugins: () => [require('autoprefixer')]
},
},
'sass-loader',
]
},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'ng-annotate-loader',
'babel-loader'
]
},
{
test: /\.html$/,
loaders: [
'html-loader'
]
}
]
},
plugins: [
new webpack.ProvidePlugin({
moment: 'moment',
agGrid: 'ag-grid'
}),
new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /js$/),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
FailPlugin,
new HtmlWebpackPlugin({
template: conf.path.src('index.html')
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: () => [autoprefixer]
},
debug: true
})
],
devtool: 'source-map',
output: {
path: path.join(process.cwd(), conf.paths.tmp),
filename: 'index.js'
},
entry: `./${conf.path.src('index')}`
};
Below is my index.js file.
import angular from 'angular';
import 'angular-sanitize';
import 'angular-toastr';
import 'todomvc-app-css/index.css';
import {TodoService} from './app/todos/todos';
import {App} from './app/containers/App';
import {Header} from './app/components/Header';
import {MainSection} from './app/components/MainSection';
import {TodoTextInput} from './app/components/TodoTextInput';
import {TodoItem} from './app/components/TodoItem';
import {Footer} from './app/components/Footer';
import 'angular-ui-router';
import 'angular-strap';
import 'angular-cookies';
import '#exalink/ui-components/dist/xl.ui-components';
import routesConfig from './routes';
import * as agGrid from 'ag-grid';
import './index.scss';
agGrid.initialiseAgGridWithAngular1(angular);
angular
.module('app', ['ngSanitize', 'ngCookies', 'agGrid', 'mgcrea.ngStrap', 'ui.router', 'toastr', 'xl.uiComponents'])
.config(routesConfig)
.service('todoService', TodoService)
.component('app', App)
.component('headerComponent', Header)
.component('footerComponent', Footer)
.component('mainSection', MainSection)
.component('todoTextInput', TodoTextInput)
.component('todoItem', TodoItem);
Below is my header.html, am adding the below template that uses bs-tabs from angular-strap.
<div bs-active-pane="$ctrl.tabs.activeTab" bs-tabs>
<div ng-repeat="tab in $ctrl.tabs" data-title="{{ tab.title }}" name="{{ tab.title }}" disabled="{{ tab.disabled }}" ng-bind="tab.content" bs-pane>
</div>
</div>
I believe am missing something pretty straight forward and simple. Am pretty new to webpack and any help would be appreciated.

You imported only
import 'angular-strap';
but still need to include angular-strap.tpl.min.js
http://mgcrea.github.io/angular-strap/
import 'angular-strap.tpl.js' as well

Related

Issue in configure the scss with bootstrap in react project

I am learning react and currently facing the issue in configuring the scss with bootstrap in a project, that was initially built by my friend and now I want to work on it. It works fine when I configure it for bootstrap. But when I try to configure the scss I have the following type error..
1)Here is the terminal error
ERROR in ./client/styles/styles.scss
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #import '~bootstrap/scss/bootstrap.scss';
| $btn-font-weight:bold;
|
# ./client/App.js 17:0-31
# ./client/main.js
# multi react-hot-loader/patch webpack-hot-middleware/client?reload=true ./client/main.js
2/ Here is my webpack.config file:
const path = require('path')
const webpack = require('webpack')
const CURRENT_WORKING_DIR = process.cwd()
const config = {
name: "browser",
mode: "development",
devtool: 'eval-source-map',
entry: [
'react-hot-loader/patch',
'webpack-hot-middleware/client?reload=true',
path.join(CURRENT_WORKING_DIR, 'client/main.js')
],
output: {
path: path.join(CURRENT_WORKING_DIR , '/dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader'
]
}, {
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.scss$/,
loaders: [ 'style-loader', 'css-loader', 'sass-loader' ]
},
{
test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/,
use: 'file-loader'
}
]
}, plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
}
module.exports = config
3)Here is my app.js file
import React from 'react'
import MainRouter from './MainRouter'
import {BrowserRouter} from 'react-router-dom'
import './styles/styles.scss';
import { hot } from 'react-hot-loader';
const App = () => (
<BrowserRouter>
<MuiThemeProvider>
<MainRouter/>
</MuiThemeProvider>
</BrowserRouter>
)
export default hot(module)(App)
To achieve expected result, use below option of using loaders in below format
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]

How to use CSS Modules with webpack in React isomorphic app?

I am build an isomorphic app using react, react-router, express and webpack. Now I want to use css modules to import css.
I use import './index.css' in index.jsx, it works fine on client, but doesn't work on server rendering. The error is Error: Cannot find module './index.css'.
components/index.jsx
import React, {Component, PropTypes} from 'react';
import style from './index.css';
class App extends Component {
constructor(props, context) {
super(props, context);
}
render() {
return (
<div id="login">
// ...
</div>
);
}
};
export default App;
server/router/index.js
import url from 'url';
import express from 'express';
import swig from 'swig';
import React from 'react';
import {renderToString} from 'react-dom/server';
import {match, RouterContext} from 'react-router';
import routes from '../../client/routes/routes';
import DataWrapper from '../../client/container/DataWrapper';
import data from '../module/data';
const router = express.Router();
router.get('*', async(req, res) => {
match({
routes,
location: req.url
}, async(error, redirectLocation, props) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search);
} else if (props) {
let content = renderToString(
<DataWrapper data={data}><RouterContext {...props}/></DataWrapper>
);
let html = swig.renderFile('views/index.html', {
content,
env: process.env.NODE_ENV
});
res.status(200).send(html);
} else {
res.status(404).send('Not found');
}
});
});
export default router;
webpack.config.dev.js(for webpack-dev-server)
var webpack = require('webpack');
var config = require('./config');
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://localhost:' + config.webpackPort,
'webpack/hot/only-dev-server',
'./src/client/entry',
],
output: {
path: __dirname + '/public/js',
filename: 'app.js',
publicPath: 'http://localhost:' + config.webpackPort + '/public/js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify('development')
}
})
],
resolve: {
extensions: ['', '.js', '.jsx', '.css']
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'react-hot',
exclude: /node_modules/
}, {
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
loader: 'style-loader!css-loader?modules',
exclude: /node_modules/
}, {
test: /\.(png|woff|woff2|svg|ttf|eot)$/,
loader: 'url-loader',
exclude: /node_modules/
}]
}
}
I'd recommend using webpack to compile UI code for both client and server side in that case. Just set target: "node" in webpack config to produce bundle which can executed in Node environment.
That article might help for compiling your server side code with Webpack: http://jlongster.com/Backend-Apps-with-Webpack--Part-I
Especially on how to exclude node_modules with the externals key.
A very bare config might look like:
'use strict';
const path = require('path');
const fs = require('fs');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const rootDir = path.resolve(__dirname, '..');
const distDir = path.join(rootDir, 'dist');
const srcDir = path.join(rootDir, 'src');
const localStyles = new ExtractTextPlugin('local.css', { allChunks: true });
const nodeModules = fs.readdirSync('node_modules')
.filter(dir => !dir.startsWith('.'))
.reduce((acc, prop) => {
acc[prop] = 'commonjs ' + prop;
return acc;
}, {});
const loaders = [
{
test: /\.(js|jsx)$/,
include: srcDir,
exclude: /node_modules/,
loader: 'babel',
query: {
cacheDirectory: true,
},
},
{
test: /\.css$/,
include: srcDir,
loader: localStyles.extract(
'style',
'css?modules&localIdentName=[name]-[local]_[hash:base64:5]'
),
},
{
test: /\.json$/,
loader: 'json',
},
];
module.exports = {
target: 'node',
entry: {
server: ['server/index'],
},
output: {
path: distDir,
filename: '[name].bundle.js',
},
externals: nodeModules,
module: {
loaders,
},
plugins: [
localStyles,
],
};
Another solution (Webpack free) could be to use babel-plugin-css-modules-transform
.

React, Babel, Webpack not parsing jsx, unexpected token error [duplicate]

This question already has answers here:
babel-loader jsx SyntaxError: Unexpected token [duplicate]
(8 answers)
Closed 6 years ago.
I am trying to build my app using wepback and getting getting stuck at this unexpected token error. All the dependencies for my project are fine and upto date I am using the same project somewhere else and it is building fine but when I try to build my current code which is same it gives the error, below are config.js and error descriptions
Here is my app.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Router} from 'react-router';
import Routes from '../routes/routes';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { browserHistory } from 'react-router';
require('../Config');
injectTapEventPlugin();
window.EventEmitter = {
_events: {},
dispatch: function (event, data, returnFirstResult) {
if (!this._events[event]) return;
for (var i = 0; i < this._events[event].length; i++)
{
if(this._events[event][i])
{
var r = this._events[event][i](data);
if(returnFirstResult)
return r;
}
}
},
subscribe: function (event, callback, onlyOne) {
if (!this._events[event] || onlyOne) this._events[event] = []; // new event
this._events[event].push(callback);
}
};
// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
Here is my config.js
var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, '../project/public/js/');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var TransferWebpackPlugin = require('transfer-webpack-plugin');
var config = {
entry: {
app: path.join(__dirname, '/app/entry_points/app.jsx'),
vendor: ['react', 'radium'],
},
resolve: {
extensions: ["", ".js", ".jsx"]
},
devtool: 'source-map',
output: {
path: buildPath,
publicPath: '/js/',
filename: 'mobile.[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "mobile.vendor.js"),
new webpack.DefinePlugin({}),
new webpack.NoErrorsPlugin(),
],
module: {
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint-loader',
include: [path.resolve(__dirname, "src/app")],
exclude: [nodeModulesPath]
},
],
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath]
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
]
},
eslint: {
configFile: '.eslintrc'
},
};
module.exports = config;
This is the error I get when I try to build:
ERROR in ./app/entry_points/app.jsx
Module build failed: SyntaxError: /home/zeus/Glide/project/project-mobile/app/entry_points/app.jsx: Unexpected token (46:16)
44 | // Render the main app react component into the app div.
45 | // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
> 46 | ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
| ^
I am using react v0.14.8, react-dom v0.14.8, babel-loader ^6.2.1
i believe you need to specify the presets with babel and install the npm module babel-preset-react
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath],
query: {
presets: ['react']
}
},
...
]
you'd also want to add es2015 to that presets array if you're using it.

_angular.angular undefined error when loading angular app built by webpack

I am trying to bootstrap an AngularJS app built with Webpack. But I get the following error and the module isn't set up.
TypeError: _angular.angular is undefined
I dig into the generated code chunk and find that the _angular.angular is from
var _angular = __webpack_require__(1);
var _angularUiBootstrap = __webpack_require__(3);
_angular.angular.module('app', [_angularUiBootstrap.bootstrap]).constant('_', window._).run(function ($rootScope) {
$rootScope._ = window._;
It looks like that _angular.angular.module should be _angular.module. I probably use a wrong way to bootstrap angular, or use an incorrect Webpack configuration. Here is my code:
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var srcDir = 'static_src';
var outputDir = 'static';
module.exports = {
devtool: 'source-map',
debug: true,
entry: {
app: path.resolve(srcDir, 'app.js')
},
output: {
path: outputDir,
filename: '[name].bundle.js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: ['', '.js', '.less', '.css'],
alias: {
npm: __dirname + '/node_modules'
}
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015'],
plugins: ['syntax-decorators', 'ng-annotate']
},
exclude: /node_module/
},
{ test: /\.less$/, loader: 'to-string!css!less' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.(png|gif|jpg)$/, loader: 'file?name=images/[name].[ext]' }
]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new ExtractTextPlugin('[name].css')
]
};
app.js
import { angular } from 'angular';
import { bootstrap } from 'angular-ui-bootstrap';
angular.module('app', [bootstrap]);
I am using angular 1.5.0 and webpack 1.12.14.
Thanks in advance.
your error is in the require statement. you are using
import { angular } from 'angular';
this implies that there is an angular variable inside of the exported angular module.
what you want to use is
import angular from 'angular';
try that.

why split app and vendor js code fails in webpack & react

My app.js requires react.
I am following the following instructions to split the app and react code: https://webpack.github.io/docs/code-splitting.html#split-app-and-vendor-code.
Unfortunately, webpack generate app.bundle.js and vendors.bundle.js; both contains react.js library, which is not desired.
I am expecting webpack to generate a small app.bundle.js(which does not contains react) and a large vendor.js(which contains react), according to the link post above.
My webpack configure file:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app: "./app.js",
vendors: ['react']
},
output: {
filename: '[name].bundle.js' // Notice we use a variable
},
plugin: [
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendors", /* filename= */"vendor.js")
],
module: {
preLoaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'source-map'
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loaders: [
'react-hot',
'babel?presets[]=stage-0,presets[]=react,presets[]=es2015'
]
}
]
}
};
My app.js file:
// Import React and JS
var React = require('react')
React.render(
React.createElement('h1', null, 'Hello, world!'),
document.getElementById('example')
);
Any suggestion is highly appreciated.
plugins: [
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendors", /* filename= */"vendor.js")
]
Use plugins, not plugin.

Resources