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

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.

Related

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

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

Webpack build issue with mobx and mobx-react

I have a project that uses React and Mobx with Mobx-react.
My project runs perfectly fine locally. However, when built using webpack -p, I get a blank screen with the following error in the console:
webpack:///./~/mobx-react/index.js?:3 Uncaught Error: Cannot find module "mobx"
at webpackMissingModule (webpack:///./~/mobx-react/index.js?:3)
at webpackUniversalModuleDefinition (webpack:///./~/mobx-react/index.js?:3)
at eval (webpack:///./~/mobx-react/index.js?:10)
at Object.<anonymous> (bundle.js:18)
at n (bundle.js:1)
at eval (webpack:///./src/components/Category.jsx?:35)
at Object.<anonymous> (bundle.js:27)
at n (bundle.js:1)
at eval (webpack:///./src/components/CategoryNavsDates.jsx?:15)
at Object.<anonymous> (bundle.js:14)
Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer')
var CopyWebpackPlugin = require('copy-webpack-plugin');
var BUILD_DIR = path.resolve(__dirname, 'build/');
var SOURCE_DIR = path.resolve(__dirname, 'src/');
module.exports = {
devtool: 'eval',
entry: SOURCE_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
plugins: ['transform-decorators-legacy'],
presets: ['es2015', 'stage-0', 'react']
}
},
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: "[name]__[local]___[hash:base64:3] "} },
{ loader: 'postcss-loader', options: {} },
]
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
postcss: function () {
return [
require('postcss-import'),
require('postcss-cssnext'),
];
},
}
}),
new CopyWebpackPlugin([{ from: 'index.html', to: '' },])
],
devServer: {
historyApiFallback: true
},
};
There is only one file using Mobx in my entire project, and that is the file the error refers to, Category.jsx.
Category.jsx sample:
import { observer } from 'mobx-react'
import { observable } from 'mobx'
...
#observer class Category extends React.Component {
#observable showingSmallMenu = false
...
}
As I say this all works perfectly fine locally.
What could be the problem here?
Does it make a difference if you import mobx before mobx-react?
In my case, that is caused by:
alias: {
mobx: __dirname + '/node_modules/mobx/lib/mobx.es6.js'
}
Remove mobx alias, then the problem is solved

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.

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.

Webpack doesn't correctly load my files

I'm totally new to webpack and I'm doing my first configuration for a new project.
I'm trying to load my jsx/scss file but I've this problem:
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var cssExtractTextPlugin = new ExtractTextPlugin("css", "index.css");
var staticPrefix = path.join(__dirname, 'src')
var distPath = path.join(__dirname, 'dist')
module.exports = {
devtool: 'eval',
//context: path.join(__dirname, staticPrefix),
entry: {
'app': ['webpack-hot-middleware/client', path.join(__dirname, 'src/app.jsx')],
'vendor': [
'bootstrap/js/dropdown',
'bootstrap/js/tab',
'bootstrap/js/tooltip',
'bootstrap/js/alert',
'jquery',
'react-router',
'react-bootstrap'
],
'myapp': path.join(__dirname, 'src/stylesheets/base.scss') //'stylesheets/base.scss'
},
output: {
path: distPath,
filename: '[name].js',
libraryTarget: 'var',
library: 'exports',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'root.jQuery': 'jquery'
}),
new ExtractTextPlugin('[name].css')
],
module: {
loaders: [
{
test: /\.js$/,
loader: ['babel'],
include: path.join(__dirname, staticPrefix),
exclude: /(vendor|node_modules)/
},
{
test: /\.jsx$/,
loader: ['babel'],
include: path.join(__dirname, staticPrefix),
exclude: /(vendor|node_modules)/
},
{
test: /\.scss$/,
include: path.join(__dirname, staticPrefix),
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader-loader')
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg)($|\?)/,
loader: 'file-loader?name=' + '[name].[ext]'
}
]
},
postcss: function() {
return [autoprefixer];
},
resolve: {
modulesDirectories: [path.join(__dirname, staticPrefix), 'node_modules'],
extensions: ['', '.jsx', '.js']
},
};
The problem is that when I run: node_modules/.bin/webpack --config=webpack.config.dev it give me 2 errors:
ERROR in ./src/app.jsx
Module parse failed: /Users/work/Desktop/myapp-client/src/app.jsx Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import React from 'react';
| console.log('hello!’);
|
# multi app
ERROR in ./src/stylesheets/base.scss
Module parse failed: /Users/work/Desktop/myapp-client/src/stylesheets/base.scss Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.
| body {
| background: black;
| }
Where I'm doing wrong ?
With babel 6 you need to include the babel react preset to transpile your .jsx files. You also need to add the babel es2015 preset to transpile ES2015, i.e. ES6, syntax:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets:[ 'react', 'es2015' ]
}
}
]
}
On a side note, if you tweak your regex in the test key, you don't need two loader entries (for the .js and .jsx files).
Make sure you install these presets separately:
npm i -D babel-preset-es2015 babel-preset-react
More info on the babel 6 changes can be found here

Resources