unable to call jQuery - javascript

Probably this is a total beginner question.
I am unable to call jQuery from within an aurelia model. I'm using the JavaScript Services SPA template. Any call to jQuery fails. I tried different approaches to fix this, but was unable to get it to work.
following are the related files :
webpack.config.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var AureliaWebpackPlugin = require('aurelia-webpack-plugin');
var bundleOutputDir = './wwwroot/dist';
module.exports = {
resolve: { extensions: [ '.js', '.ts' ] },
entry: { 'app': 'aurelia-bootstrapper-webpack' }, // Note: The aurelia-webpack-plugin will add your app's modules to this bundle automatically
output: {
path: path.resolve(bundleOutputDir),
publicPath: '/dist',
filename: '[name].js'
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts-loader', query: { silent: true } },
{ test: /\.html$/, loader: 'html-loader' },
{ test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
{ test: /\.json$/, loader: 'json-loader' }
]
},
plugins: [
new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new AureliaWebpackPlugin({
root: path.resolve('./'),
src: path.resolve('./ClientApp'),
baseUrl: '/'
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
};
webpack.config.vendor.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
module.exports = {
resolve: {
extensions: [ '.js' ]
},
module: {
loaders: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader?limit=100000' },
{ test: /\.css(\?|$)/, loader: extractCSS.extract(['css-loader']) }
]
},
entry: {
vendor: [
'aurelia-event-aggregator',
'aurelia-fetch-client',
'aurelia-framework',
'aurelia-history-browser',
'aurelia-logging-console',
'aurelia-pal-browser',
'aurelia-polyfills',
'aurelia-route-recognizer',
'aurelia-router',
'aurelia-templating-binding',
'aurelia-templating-resources',
'aurelia-templating-router',
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'jquery'
],
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
publicPath: '/dist/',
filename: '[name].js',
library: '[name]_[hash]',
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
};
and the TypeScript model
import { $, jQuery} from 'jquery';
export class Home {
private a: jQuery;
attached() {
alert("begin");
this.a = $("body"); // this line fails
alert("end");
}
}

The comment from Kelly did the trick:
Try importing it like import * as $ from 'jquery';

Related

Can't load templates with routeprovider when using webpack

I recentley migrated from grunt to webpack and I can't figure how to require/import my templates. I have looked at several similar issues with no luck.
Here is my webpack.config file:
var webpack = require('webpack');
var globby = require('globby');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: globby.sync(['./app/app.js','./app/app.run.js', './app/app.config.js', './app/**/*.js']),
styles: globby.sync(['./content/styles/*.css']),
images: globby.sync(['./content/images/*.*']),
vendor: [
// removed to save space
]
},
output: {
filename: './scripts/[name].bundle.js',
path: path.join(__dirname, "public")
},
devServer: {
port: 1384,
contentBase: './public/'
},
// Enable sourcemaps for debugging webpack's output.
devtool: 'source-map',
module: {
rules: [
{ test: /\.less$/,
loader: "less-loader",
include: path.resolve(__dirname, "content", "styles", "less")
},
{
test: /\.html$/,
use: [
{
loader: 'ngtemplate-loader',
options: {
angular: true,
},
},
{
loader: 'raw-loader',
},
{
loader: 'html-loader'
},
{
loader: "ngtemplate!html?module=myTemplates&relativeTo=" +
(path.resolve(__dirname, './app/**'))
},
],
/*
exclude: [/node_modules/]
*/
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }),
},
{
test: /\.(ico)$/,
loader: "url-loader?name=./[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.(jpg|jpeg|gif|png|tiff|svg)$/,
loader: "file-loader?name=./images/[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?minetype=application/font-woff&name=./fonts/[name].[ext]'
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader?name=./fonts/[name].[ext]'
},
{
test: require.resolve('adal-angular/lib/adal'),
loader: 'expose-loader?AuthenticationContext'
},
{
test: /\.js$/,
enforce: "pre",
loader: 'source-map-loader'
}
],
},
plugins: [
new webpack.DefinePlugin({
ADMIN_API_URL: JSON.stringify('http://localhost:41118/api/'),
API_URL: JSON.stringify('http://localhost:32605/api/'),
GLOBAL_ADMIN_URL: JSON.stringify('https://adminapi.tradesolution.no/')
}),
new HtmlWebpackPlugin({
template: './app/layout.ejs',
filename: 'index.html'
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: './scripts/vendor.bundle.js' }),
new ExtractTextPlugin({ filename: './styles/[name].bundle.css' }),
/*new CleanWebpackPlugin(['public'], {
verbose: false
}),
*/
new AssetsPlugin({
filename: 'webpack.assets.json',
path: './public/scripts',
prettyPrint: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
"window.AuthenticationContext": "AuthenticationContext",
_: 'underscore'
}),
],
externals: [
{ xmlhttprequest: '{XMLHttpRequest:XMLHttpRequest}' }
],
}
The public folder builds as it should with .js, styles, images etc. But simple navigation results in this error:
ERROR in ./app/app.config.js
Module not found: Error: Can't resolve 'app/varegruppe/templates/index.html' in 'C:\Users\oystein\work\EPD.SPA\EpdSPA\app'
# ./app/app.config.js 50:25-71
Here is an example of how the routes are defined:
$routeProvider.when('/produkteier', {
templateUrl: require('app/produkteier/templates/view.html')
})
Using this plugin I managed to copy all the html files in to the public directory, with the following config:
var CopyWebpackPlugin = require('copy-webpack-plugin');
new CopyWebpackPlugin([
{from: './app/**/*.html', to: './'}
])

webpack jquery plugin perfect-tooltip

I'm trying to load the perfect-tooltip jquery plugin (http://tborychowski.github.io/perfecttooltip/) using webpack.
I successfully loaded other jquery plugins like: typed.js and backstretch by following the instructions provided here (Managing jQuery plugin dependency in webpack) but they don't seem to work with that specific plugin.
When I run the bundle an error tells me that the tooltip function (exported by the plugin) is not defined. It seems the plugin is not loaded by jquery. I thought the plugin tried to load its own instance of jquery so I used an alias:
alias: {
'jquery': require('jquery'),
}
It didn't solve the problem.
My current webpack configuration:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var moment = require('moment');
var path = require('path');
var environment = process.env.APP_ENVIRONMENT || 'dev';
module.exports = {
entry: {
'app': './src/main.ts',
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts'
},
devtool: 'source-map',
output: {
path: './dist',
filename: '[name].browser.' + moment().format('DDMMYYYYHHmm') + '.js'
},
module: {
loaders: [
{ test: /\.component.ts$/, loader: 'ts!angular2-template' },
{ test: /\.ts$/, exclude: /\.component.ts$/, loader: 'ts' },
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, include: path.resolve('src/app'), loader: 'raw-loader' },
{
test: /\.css$/, exclude: path.resolve('src/app'), loader: ExtractTextPlugin.extract('style', 'css', {
fallbackLoader: "style-loader",
loader: "css-loader"
})
},
{ test: /\.(png|jpe?g|gif|ico)$/, loader: 'file?name=fonts/[name].[ext]' },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file?name=fonts/[name].[ext]" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml&name=fonts/[name].[ext]" },
]
},
resolve: {
extensions: ['', '.js', '.ts', '.html', '.css']
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new webpack.DefinePlugin({
app: {
environment: JSON.stringify(environment),
config: JSON.stringify(require('./profile/' + environment + ".profile.js"))
}
}),
new CleanWebpackPlugin(
['dist']
),
new CopyWebpackPlugin([
{ from: './src/images', to: 'images' }
]),
new ExtractTextPlugin('[name].browser.css'),
new webpack.optimize.UglifyJsPlugin({ minimize: true }),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
]
};
Any insight?
Eventually I managed to load that script.
The package.json file provided in the package doesn't have a main property, Webpack was simply trying to bundle all files in the package.
I solved that by requiring two specific files: "js/jquery.tooltip.js" and "css/tooltip.css".

Webpack doesn't catch the changes in Typescript files

I am working on an Angular project and use Webpack bundler. Everything was working fine until Webpack started to ignore my changes to Typescript files. When I change a Typescript file, Webpack first says:
[WDS] App updated. Recompiling...
followed by:
[WDS] Nothing changed.
Also, killing webpack-dev-server and rebuilding the sources doesn't make any difference. The changes I make to TS files are not applied in any way.
EDIT: Loader setup on request (which is exactly the same as in the Angular Developer Guide):
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['', '.js', '.ts']
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
webpack.dev.js:
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});

Webpack aliases do not work

I set resolve.alias in webpack.config.js
alias: {
'$': 'jquery',
'_': 'underscore'
}
and require modules in my javascript file like this.
var $ = require('$');
var _ = require('_');
then there comes an error
Module not found: Error: Cannot resolve module '$'
I try to display error details and I find out that it still try to looking for modules named $ or _, not jquery or underscore.
So why doesn't the alias config work? Do I set a wrong config?
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = require('../config');
var projectRoot = path.resolve(__dirname, '../');
var buildPath = path.resolve(__dirname, 'demo');
module.exports = {
// eval-source-map is faster for development
devtool: '#eval-source-map',
entry: {
miceui: ['webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server',
path.resolve(projectRoot, 'index')]
},
output: {
path: buildPath,
filename: '[name].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
new ExtractTextPlugin('[name].css'),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
],
module: {
loaders: [
{ test: /\.htm(l?)$/, loader: 'html-loader' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' }
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.coffee', '.html', '.css', '.scss'],
alias: {
'$': 'jquery',
'_': 'underscore'
}
}
};

webpack production setup - vendors output js always has different chunk hash even though nothing's changed

The follow production webpack.config file mostly works (builds, runs ok), but one nagging problem. I set up vendor and app js outputs precisely to separate vendor code (since those don't change very often). However, with the .config setup, even if there is no change, I always get a different chunk hash for vendor and app.js. I must be setting this wrong somehow but I have no idea what it could be. Please help!
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var AssetsPlugin = require('assets-webpack-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var app_dir = path.join(__dirname, 'app');
var config = {
entry: {
vendors: ['react', 'react-dom', 'moment'],
app: path.resolve(__dirname, 'app/Main.js')
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
loaders: [{
test: /\.jsx?$/, // A regexp to test the require path. accepts either js or jsx
exclude: [node_modules_dir],
loader: 'babel', // The module to load. "babel" is short for "babel-loader"
},
// LESS
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.css$/, // Only .css files
loader: 'style!css' // Run both loaders
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
},
{ test: /\.gif$/, loader: "url-loader?mimetype=image/png" },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[name].[ext]" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendors",
minChunks: Infinity
}),
new AssetsPlugin({
filename: 'webpack-assets.js',
path: path.resolve(__dirname, 'dist'),
processOutput: function (assets) {
return 'window.staticMap = ' + JSON.stringify(assets);
}
}),
new ChunkManifestPlugin({
filename: "chunk-manifest.json",
manifestVariable: "webpackManifest"
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
},
'__appSettings': {
'apiGatewayDomain': '"http://localhost:8088"',
'enableDevTools': false,
'enableReduxLogger': false
},
__version: JSON.stringify(require(__dirname +"/package.json").version)
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!isomorphic-fetch',
'configureApplicationStore': 'exports?configureStore!' + app_dir + '/global/redux/ConfigureStore.prod.js'
})
]
};
module.exports = config;
If there are other glaring issues with this setup, please let me know as well. Thanks!
use the "key sort" to fixed vendor.
you entry just like this:
entry: {
a_vendors: ['react', 'react-dom', 'moment'],
z_app: path.resolve(__dirname, 'app/Main.js')
},
the vendor will fixed.
more detail:
https://github.com/webpack/webpack/issues/1315#issuecomment-247269598
https://github.com/webpack/webpack/pull/2998

Categories