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'
}
}
};
Related
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: './'}
])
I am new to webpack & want to add all the css files bundled and added to to the index.html file in dist.
my webpack.config.js file
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const helpers = require('./helpers');
module.exports = function(env) {
return {
entry: {main:'./app/index.js',
vendor: 'moment'
},
resolve: {
extensions: ['.css', '.js']
},
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.css$/,
include: helpers.root('app'),
use: ExtractTextPlugin.extract({
fallback: "css-loader",
use: 'style-loader'
})
},
{
test: /\.html$/,
loader: 'html-loader'
}
]},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', , 'manifest']
}),
new ExtractTextPlugin('styles.css'),
new HtmlWebpackPlugin({
template: 'app/index.html',
inject: 'body'
})
]
}
};
However it does not create styles.css file.
Thanks in advance.
webpack.config.js:
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const CleanWebpackPlugin = require('clean-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
module.exports = function (env) {
return {
devServer: {
inline: true
},
resolve: {
extensions: ['.html', '.css', '.js', '.json'],
modules: ['node_modules'],
},
devtool: 'source-map',
context: __dirname,
entry: {
landing: [
'./js/landing.js'
]
},
output: {
path: path.resolve(__dirname, './app/'),
filename: '[name].js',
chunkFilename: '[id].js',
pathinfo: true,
sourceMapFilename: '[file].map'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
},
{
test: /\.html$/,
use: 'html-loader'
},
{
test: /\.(eot|woff|ttf|svg|png|jpg)$/,
use: 'url-loader?limit=50000&name=assets/[name]-[hash].[ext]'
}
]
},
plugins: [
new CleanWebpackPlugin(['app']),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
_: 'lodash',
jPlayer: 'jplayer'
}),
new ExtractTextPlugin({
filename: (getPath) => {
return getPath('css/[name].css');
},
allChunks: true
}),
new HtmlWebpackPlugin({
filename: 'index.html',
chunks: ['landing', 'bundle'],
favicon: './img/favicon.png',
template: './pages/index.html',
inject: true
}),
new HtmlWebpackPlugin({
filename: 'terms.html',
chunks: ['terms', 'bundle'],
favicon: './img/favicon.png',
template: './pages/terms.html',
inject: true
}),
new CommonsChunkPlugin('bundle')
]
};
};
landing.js:
import $ from '../node_modules/jquery';
window.$ = $;
window.jQuery = $;
jQuery = $;
import '../node_modules/owl.carousel';
I used the command: webpack --env=prod --config=webpack.config.js
After running the command I open the page /app/index.html in the browser
But the error on the page:
Uncaught TypeError: Cannot read property 'fn' of undefined
at owl.carousel.js:1658
1658: $.fn.owlCarousel = function(option) {
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';
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'
}
});