Karma + PhantomJS - window is not defined - phantomjs

I am using Karma and PhantomJS for a headless browser. For some reason, I keep getting an error saying window is not defined.
My karma.conf.js
var path = require('path');
var webpack = require('webpack');
var webpackConfig = require('./config/webpack/webpack.config');
webpackConfig.module = {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: path.join(__dirname, 'app/frontend')
},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.css$/, loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]' },
{ test: /\.scss$/, loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]!resolve-url!sass?outputStyle=expanded' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' } // inline base64 URLs for <=8k images, direct URLs for the rest
],
noParse: [
/node_modules\/sinon\//
]
};
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ],
singleRun: true, //just run once by default
frameworks: [ 'mocha' ], //use the mocha test framework
files: [
'app/frontend/.config/karma/test.bundle.js' //just load this file
],
preprocessors: {
'app/frontend/.config/karma/test.bundle.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader
},
reporters: [ 'dots' ], //report results in this format
webpack: webpackConfig,
colors: true,
webpackServer: {
noInfo: true
},
phantomjsLauncher: {
exitOnResourceError: true
}
});
};
And here's the error I get:
I'm not sure why window object is not available even though I use PhantomJS as the launcher. Any help would be greatly appreciated.

Related

Webpack 5: how to disable copying static files to build folder?

I am used webpack 2 for project, and some days ago I have upgraded to version 5.6.
2-3 hours and project compiling OK, but I have just one problem.
All static files (images, fonts) I store in /static/ folder.
CSS file:
.link-yellow{
background-image: url("/static/wifi2.png");
}
.link-red{
background-image: url("/static/wifi4.png");
}
.link-grey{
background-image: url("/static/wifi3.png");
}
Webpack 2 after compiling JS bundle file don't touch css url(...) links but webpack 5 copying files to folder /build/ and finally I have this:
4e4b4524859364a45966.png
5b97c8a6a9b9aa05b4be.otf
7ed064d8178174fa9ce1.woff2
14d3902c59ccd98328c8.png
440e51cee01b3e78fed5.png
664550a92a1dbb39a80a.png
build.js
And this records (like 4e4b4524859364a45966.png) in build.js:
...3197:function(t,e,n){"use strict";t.exports=n.p+"4e4b4524859364a45966.png"}...
Build progress:
I tried to use file-loader with this params:
module: {
rules: [
....
{
test: /\.(png|svg|jpg|jpeg|gif|gif|woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options:{
emitFile: false,
name: '[name].[ext]'
}
}
....
]
}
but after that I have the same files in /build/ folder with texts inside like this:
export default __webpack_public_path__ + "wifi2.png";
export default __webpack_public_path__ + "exo2.otf";
export default __webpack_public_path__ + "wifi3.png";
I moved some images files to style="..." attributes in vue files:
<div id="mainFooter" style="background: transparent url('/static/wifi3.png') no-repeat 0 0">
and webpack don't touch this text and not generate copies of static files in /build/ folder and all works fine. It is that I need.
Full source of webpack.config.js:
var path = require('path');
var webpack = require('webpack');
const { VueLoaderPlugin } = require('vue-loader');
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
mode: 'production',
plugins: [
new VueLoaderPlugin()
],
module: {
rules: [
{
test: /\.styl$/,
use: ['style-loader', 'css-loader', 'stylus-loader']
},
{
test: /\.css$/,
use: ['vue-style-loader','css-loader']
},
{
test: /\.scss$/,
use: ['vue-style-loader','css-loader','sass-loader'],
},
{
test: /\.sass$/,
use: ['vue-style-loader','css-loader','sass-loader?indentedSyntax'],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
],
'sass': [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|jpeg|gif|gif|woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options:{
emitFile: false,
name: '[name].[ext]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
client: {
overlay: true,
},
static: './'
},
performance: {
hints: false
},
devtool: 'eval-source-map',
optimization: {
minimize: true,
portableRecords: true,
removeAvailableModules: true,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
format: {
comments: false,
},
},
extractComments: false
})
]
}
};
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = 'inline-nosources-cheap-source-map';//source-map
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Maybe someone know how to disable generating static files in /build/ folder and leave files url's in css with no modifying paths?
UPDATE:
I have some progress. Code disabling touching urls in css files, but fonts still copying:
{
test: /\.css$/,
use: ['vue-style-loader']
},
{
test: /\.css$/,
loader: 'css-loader',
options: {
url: false,
},
},
UPDATE2: Done. Adding:
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
type: "asset",
}
finally disabling generate other files. At now generating only /build/build.js file

vue environmental variables return empty object

I am new to vue and webpack, When I console.log(process.env. VUE_APP_API_URL) in my vue application, an empty object returns. I have a .env.development file with:
VUE_APP_API_URL=http://localhost:8000/api
The application backend is built in laravel which works fine. But I want to be able to store the api url as an environment variable.
My webpack.config.js
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
],
},
{
test: /\.sass$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
],
'sass': [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
},
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}),
])
}
I tried running npm install dotenv-webpack --save-dev and add it the webpack plugins but it still didnt resolve the issue.
How do I resolve this issue?
In order to load the configuration from your .env file you need to first install the dotenv dependency, and call require("dotenv").config() before calling your variable. This will load the variables and make them available using process.env.YOUR_VARIABLES

How to define the right Preset When using Nuxt in order to run on IE

I'm trying to run my VueJS + Nuxt app on IE and get the following error:
'Unable to get property 'call' of undefined or null reference'
This happens in the following line:
modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
when moduleID = "./node_modules/webpack-hot-middleware/client.js?name=client&reload=true&timeout=30000&path=/__webpack_hmr"
I think it has something to do with the way I configure my presets when using Nuxt.
This is currently how nuxt.config.js build part looks like:
build: {
vendor: ['vuetify', 'babel-polyfill', 'vued3tree', 'vue2-editor','lodash'],
extractCSS: true,
babel: {
presets: [
['es2015'],
[
'vue-app',
{
useBuiltIns: true,
targets: { ie: 11, uglify: true },
},
],
],
},
How do I need to configure my presets in order for my app to run on IE?
solved that as well by removing a library called vue2-hammer. Now I have one issue in Chrome and in IE: 'regeneratorRuntime is not defined'. tried every solution in Google and no solution. Now my Nuxt.config.js looks like this:
const polyfill = require('#babel/polyfill');
module.exports = {
entry: [polyfill],
build: {
extractCSS: true,
extend(config, ctx) {
if (ctx.isDev && ctx.isClient) {
config.module.rules.push(
{
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
},
{
test: /\.js$/,
loader: 'babel-loader',
options: {
plugins: [
[
'#babel/plugin-transform-runtime',
{
corejs: false,
helpers: true,
regenerator: true,
useESModules: false,
},
],
[
'#babel/plugin-transform-regenerator',
{
asyncGenerators: false,
generators: false,
async: false,
},
],
'babel-plugin-transform-es2015-shorthand-properties',
'#babel/plugin-transform-exponentiation-operator',
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-transform-arrow-functions',
],
},
},
);
}
},
},
babel: {
presets: [
[
'es2015',
'stage-0',
],
],
exclude: ['transform-regenerator'],
},
Ant idea what can cause this?

How to include node module for Babel using Webpack

when running
npm run build
I encounter an es6 related syntax error from uglify, so I'm guessing babel isn't handling the node module (sec-to-min) properly.
My .babelrc
{
"presets": ["es2015", "stage-0"],
"plugins": ["transform-runtime"],
"comments": false,
"env": {
"test": {
"plugins": [ "istanbul" ]
}
}
}
My Webpack config:
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')
var env = process.env.NODE_ENV
// check env & config/index.js to decide whether to enable CSS source maps for the
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue', '.json'],
fallback: [path.join(__dirname, '../node_modules')],
alias: {
'vue$': 'vue/dist/vue.common.js',
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components')
}
},
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
include: [
path.join(projectRoot, 'src')
],
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
include: [
path.join(projectRoot, 'src')
],
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
include: [
path.join(projectRoot, 'src'),
'node_modules/sec-to-min'
],
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
eslint: {
formatter: require('eslint-friendly-formatter')
},
vue: {
loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }),
postcss: [
require('autoprefixer')({
browsers: ['last 2 versions']
})
]
}
}
& the ERR:
ERROR in static/js/vendor.8d64852626f0513309d9.js from UglifyJs
SyntaxError: Unexpected token: operator (>)
[./~/sec-to-min/index.js:3,0]
How can I direct babel to compile this module?
please note that on Windows the slashes in the path will be \ so the above solution would have to be changed to exclude: /node_modules\\(?!(sec-to-min)\/).*/
This was the solution that worked for me, with webpack 4.3 and babel-loader 8.0.5, and using the recommended #babel/preset-env, adapted from here https://github.com/webpack/webpack/issues/2031#issuecomment-283517150
{
test: /\.(js|jsx|mjs)$/,
include: [paths.appSrc, paths.appNodeModules],
exclude: function(modulePath) {
return (
/node_modules/.test(modulePath) &&
!/node_modules\\react-dev-utils/.test(modulePath)
);
},
loader: require.resolve('babel-loader'),
options: {
compact: true,
presets: ['#babel/preset-env']
}
},
I found it helpful to use the function for exclude as I was able to add console logs within the function to check which modules were being matched by the regex.
In babel section of webpack config change to this :
{
test: /\.js$/,
loader: 'babel',
include: [
path.join(projectRoot, 'src')
],
exclude: /node_modules\/(?!(sec-to-min)\/).*/
}
Looks like exclude has priority over include.
Install following packages
npm install babel-preset-es2015 --save-dev
npm install babel-preset-stage-0 --save-dev
Add es2015 and stage-0 in your babel presets
{
"presets": ["es2015", "stage-0"],
}
UPDATE
Try this
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react', 'stage-0'],
},
},
include: [
path.join(projectRoot, 'src'),
'node_modules/sec-to-min'
],
exclude: /node_modules/
},
Work for me in Webpack v4:
rules: [{
include: [
path.resolve(__dirname, 'src'),
/node_modules\/(dom7|swiper)/
],
loader: 'babel-loader',
presets: [['#babel/preset-env', {
'modules': false
}]]
},
test: /\.(js)$/
}]

less-loader issue with webpack

I have an issue with loading flat-ui.less from the module. Need help.
I require flat-ui like this require('flat-ui/less/flat-ui.less'); Also the versions for each related loader are "less-loader": "^0.7.7", "css-loader": "^0.9.0", "style-loader": "^0.8.1",
My webpack.config.js is like this:
var path = require("path");
var webpack = require("webpack");
module.exports = {
// This is the main file that should include all other JS files
entry: "./public/scripts/main.jsx",
target: "web",
debug: true,
devtool: "source-map",
// We are watching in the gulp.watch, so tell webpack not to watch
watch: true,
watchDelay: 300,
output: {
path: path.join(__dirname, "dist", "assets"),
publicPath: "/assets/",
// If you want to generate a filename with a hash of the content (for cache-busting)
// filename: "main-[hash].js",
filename: "main.js",
chunkFilename: "[chunkhash].js"
},
resolve: {
// Tell webpack to look for required files in bower and node
modulesDirectories: ['bower_components', 'node_modules', 'public'],
fallback: ['./public']
},
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.less$/, loader: "style-loader!css-loader!less-loader" },
{ test: /\.gif/, loader: "file-loader!url-loader?limit=10000&minetype=image/gif" },
{ test: /\.jpg/, loader: "file-loader!url-loader?limit=10000&minetype=image/jpg" },
{ test: /\.png/, loader: "file-loader!url-loader?limit=10000&minetype=image/png" },
{ test: /\.jsx/, loader: "jsx-loader" },
// required for bootstrap/flat-ui
{ test: /\.woff$/, loader: "url-loader?prefix=font/&limit=5000&mimetype=application/font-woff" },
{ test: /\.ttf$/, loader: "file-loader" },
{ test: /\.eot$/, loader: "file-loader" },
{ test: /\.svg$/, loader: "file-loader" },
],
noParse: /\.min\.js/
},
plugins: [
// If you want to minify everything
new webpack.optimize.UglifyJsPlugin()
]
};
Unfortunately, I got this
ERROR in ./~/css-loader!./~/less-loader!./~/flat-ui/less/flat-ui.less
Module not found: Error: Cannot resolve 'file' or 'directory' ./fonts/lato/lato-black.eot in /Users/Hao/Documents/project/node_modules/flat-ui/less
# ./~/css-loader!./~/less-loader!./~/flat-ui/less/flat-ui.less 2:66-104 2:118-156
Any idea of what's going on here??
Thanks in advance.
The issue here is that your application is looking for lato-black.eot in /Users/Hao/Documents/project/node_modules/flat-ui/less, but it's not there. That's because it's being created somewhere else, I'm guessing /Users/Hao/Documents/project/public. In any case, find where it is being created, then add this to your webpack.config.js:
{ test: /\.eot$/, loader: "file-loader&name=./path/to/file/[hash].[ext]" }
This will tell your application where to look for all eot files. You can do the same with all the other file types as well. Here's a link to the closed issue on the webpack github: https://github.com/webpack/file-loader/issues/32. Hope this helps.