Trying to use Mocha frameworks with Karma Runner on reactJs application.
some reason I have a following error messages :
Module parse failed: C:\Dev\marvel-memory-card-v2\src\index.scss Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
Uncaught Error: Cannot find module "./index.scss" at tests.webpack.js:22214
Since everything is pretty new to me. No idea How to solve this issue.
Here is my webpack.config files :
"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";
// global css
loaders.push({
test: /\.css$/,
exclude: /[\/\\]src[\/\\]/,
loaders: [
'style?sourceMap',
'css'
]
});
// local scss modules
loaders.push({
test: /\.scss$/,
exclude: /[\/\\](node_modules|bower_components|public\/)[\/\\]/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]&sourceMap',
'postcss',
'sass'
]
});
// local css modules
loaders.push({
test: /\.css$/,
exclude: /[\/\\](node_modules|bower_components|public\/)[\/\\]/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]&sourceMap'
]
});
module.exports = {
entry: [
'react-hot-loader/patch',
'./src/index.jsx' // your app's entry point
],
devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
output: {
publicPath: '/',
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders
},
devServer: {
contentBase: "./public",
// do not print bundle build stats
noInfo: true,
// enable HMR
hot: true,
// embed the webpack-dev-server runtime into the bundle
inline: true,
// serve index.html in place of 404 responses to allow HTML5 history
historyApiFallback: true,
port: PORT,
host: HOST
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
new DashboardPlugin(),
new HtmlWebpackPlugin({
template: './src/template.html'
}),
]
};
and karma.conf file
var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
singleRun: true,
frameworks: ['mocha'],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': ['webpack']
},
reporters: ['dots'],
webpack: {
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}
]
},
watch: true
},
webpackServer: {
noInfo: true
}
});
};
Any idea to solve my issue ? Please let me know.
Huge Thanks
Try to add this line to your karma configuration:
basePath : __dirname + '/',
and this is the scss loader for webpack:
{
test: /\.scss$/,
exclude: /[\/\\](node_modules|bower_components|public\/)[\/\\]/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]&sourceMap',
'postcss',
'sass'
]
}
So your file should look like this:
module.exports = function (config) {
config.set({
basePath : __dirname + '/',
browsers: ['Chrome'],
singleRun: true,
frameworks: ['mocha'],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': ['webpack']
},
reporters: ['dots'],
webpack: {
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'},
{
test: /\.scss$/,
exclude: /[\/\\](node_modules|bower_components|public\/)[\/\\]/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]&sourceMap',
'postcss',
'sass'
]
}
]
},
watch: true
},
webpackServer: {
noInfo: true
}
});
};
Related
I am using webpack-hot-middleware for hot module replacement for javascript ui scripts in an express app. Whenever I start the server, I get this error:
Module not found: Error: Can't resolve 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true'.
Here is my webpack config, which I compile in the webserver:
const path = require('path');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: [ path.join(__dirname, 'ui/lib/utilities/index.js') , 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true' ],
output: {
path: path.join(__dirname, 'ui/dist'),
filename: '[name].js',
publicPath: 'http://localhost:3000'
},
resolve: {
extensions: [
'.js',
],
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/, // exclude any and all files in the node_modules folder
include: path.resolve(__dirname, 'scripts'),
use: [
{
loader: 'babel-loader',
options: {
presets: ['env', 'es2015'],
plugins: [
// OccurrenceOrderPlugin is needed for webpack 1.x only
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
// Use NoErrorsPlugin for webpack 1.x
new webpack.NoEmitOnErrorsPlugin()
],
camelcase: true,
emitErrors: false,
failOnHint: false,
},
},
{ loader: 'style-loader' },
{ loader: 'css-loader' },
],
},
],
},
};
And here's the compilation in the server code:
web.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath,
writeToDisk: true,
hot: true
}));
web.use(require("webpack-hot-middleware")(compiler, {
log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000
}));
I am coding some learning project to implement TDD, webpack.
I use webpack 2 with the following config:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
//const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
process.noDeprecation = true;
module.exports = {
entry: './src/js/index.js',
devtool: 'source-map',
context: __dirname,
target: 'web',
stats: 'errors-only',
watch: true,
output: {
path: path.resolve(__dirname, './dist'),
filename: 'js/[name].[chunkHash].js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src')
],
exclude: [
path.resolve(__dirname, 'node_modules')
],
loader: 'babel-loader',
options: {
presets: ['es2015']
},
},
{
test: /\.css$/,
/*use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})*/
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new WebpackMd5Hash(),
//new ExtractTextPlugin('[name].[contenthash].css'),
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
},
inject: true
}),
new webpack.optimize.UglifyJsPlugin()
],
devServer: {
contentBase: path.join(__dirname, "dist/"),
compress: true,
port: 8080
}
}
When I run simply webpack it compiles and works fine. But when I try to run karma with webpack preprocessor, it gives the following error:
Uncaught Error: Module parse failed: C:\Users\Javid\Desktop\projects\rejection\src\css\style.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
I use import '../css/style.css'; in my js file. Googled it a lot, didn't find a solution.
Solution
I used additionaly raw-loader to handle my css and changed my import to look like this: import css from 'raw-loader!../css/style.css';
Reference: https://angular.io/docs/ts/latest/guide/webpack.html
This site shows a good example of a project for development, test, and production builds. In particular to your question, it looks as if a loader is used to ignore the .css files when running karma.
Here is a sample of their files related to karma:
"karma.config.js":
module.exports = require('./config/karma.conf.js');
"karma.conf.js":
var webpackConfig = require('./webpack.test');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [
{pattern: './config/karma-test-shim.js', watched: false}
],
preprocessors: {
'./config/karma-test-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
reporters: ['kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
};
config.set(_config);
};
"webpack.test.js":
var webpack = require('webpack');
var helpers = require('./helpers');
module.exports = {
devtool: 'inline-source-map',
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{
loader: 'awesome-typescript-loader',
options: { configFileName: helpers.root('src', 'tsconfig.json') }
} , 'angular2-template-loader'
]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'null-loader'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: 'null-loader'
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
}
]
},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
)
]
}
I try to get my karma tests running with webpack#^2.2.1 and karma#1.4.1. But all i get is this Error:
ERROR [preprocess]: Can not load "webpack"!
Error
at webpack (/Users/plano/S/plano/projects/scheduler.frontend.ng2/node_modules/webpack/lib/webpack.js:19:9)
at new Plugin (/Users/plano/S/plano/projects/scheduler.frontend.ng2/node_modules/karma-webpack/lib/karma-webpack.js:65:18)
at invoke (/Users/plano/S/plano/projects/scheduler.frontend.ng2/node_modules/di/lib/injector.js:75:15)
...
All solutions that i found are about a bug in karma#0.12.x (e.g. this github issue and this stackoverflow quertion). Im on 1.4.1 so they aren’t helpful for me.
This post tells me to remove entry: {} from webpack config. I have no entry: {} on my webpack config.
According to this stackoverflow answer it’s an webpack issue since 2.2.0-rc.4. So i tried 2.2.0-rc.3. Nothing changed.
My karma.conf.js:
'use strict';
module.exports = config => {
config.set({
autoWatch: true,
browsers: ['Chrome', 'PhantomJS'],
files: [
'../node_modules/es6-shim/es6-shim.min.js',
'karma.entry.js'
],
frameworks: ['jasmine'],
logLevel: config.LOG_INFO,
phantomJsLauncher: {
exitOnResourceError: true
},
port: 9876,
preprocessors: {
'karma.entry.js': ['webpack', 'sourcemap']
},
reporters: ['dots'],
singleRun: true,
webpack: require('../webpack/webpack.test.js'),
webpackServer: {
noInfo: true
}
});
};
My webpack.test.js:
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'inline-source-map',
module: {
preLoaders: [
{ exclude: /node_modules/, loader: 'tslint', test: /\.ts$/ }
],
loaders: [
{ loader: 'raw', test: /\.(css|html)$/ },
{ exclude: /node_modules/, loader: 'ts', test: /\.ts$/ },
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
}
]
},
resolve: {
extensions: ['', '.js', '.ts'],
modulesDirectories: ['node_modules'],
root: path.resolve('.', 'src')
},
tslint: {
emitErrors: true
}
};
I got this error when I'd forgotten to add the webpack: option to my Karma config.
Solved.
I had an option like this in my webpack.test.js:
tslint: {
emitErrors: true
}
Webpack 2 has a very strict configuration. Now it looks like this:
plugins: [
...
new LoaderOptionsPlugin({
options: {
emitErrors: true
}
}),
]
More info here: https://github.com/gonzofish/semaphore-ng2-webpack/pull/4#issuecomment-279374763
I want to load module from variable string
var abc = './../containers/BlankContainer';
require(abc);
but it cannot find module, so I install 'require-from-string' module from npm.
Now when I build it's giving error
ERROR in ./~/require-from-string/index.js
Module not found: Error: Cannot resolve module 'module' in D:\Nilay\RnD\node_modules\require-from-string
# ./~/require-from-string/index.js 3:13-30
I found it is webpack issue, here is my webpack config:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin')
var entry = [path.resolve(__dirname, 'app/bootstrap.js')];
var output = {
path: path.resolve(__dirname, 'public/dist'),
filename: 'bundle-[name].js',
publicPath: "dist/"
};
var modules = {
loaders: [
{ test: /\.json$/, loader: "json-loader" },
{ test: /\.js$/,
loader: ['babel-loader'], exclude: /node_modules/, query: { cacheDirectory: 'babel_cache', presets: ['react', 'es2015'] } },
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader") },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.(woff|woff2)$/, loader: "file-loader" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" }
]
};
var plugins = [
new ExtractTextPlugin("bundle.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ // minimize/compress all js chunks
compress: { warnings: false },
mangle: false,
sourcemap: false,
beautify: false,
dead_code: true
})
]
module.exports = {
entry: entry,
output: output,
stats: { colors: true },
watch: true,
module: modules,
plugins: plugins,
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
resolve: {
modules: [path.resolve(__dirname, '/app/routes'), 'node_modules/'],
descriptionFiles: ['package.json'],
extensions: ['', '.js', '.ts']
}
};
How can I resolve it?
I'm trying to create an universal react app (using webpack both on server and on the client) and struggle with images import. I want to write this :
import someImage from './someImage.png'
const SomeImage = () => <img src={someImage}/>
Here's my webpack config file:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./client',
'babel-polyfill'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
modulesDirectories: ['node_modules', 'shared'],
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel']
},
{
test: /\.css/,
exclude: /node_modules/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?emitFile=false',
]
}
]
},
plugins: [
new ExtractTextPlugin('styles.css', { allChunks: true }),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
devtool: 'inline-source-map',
devServer: {
hot: true,
proxy: {
'*': 'http://127.0.0.1:' + (process.env.PORT || 3000)
},
host: '127.0.0.1'
}
};
Obviously it's not working server side because node try to read the content of the ./someImage.png file, resulting in an error.
How can I handle this ? I know there are packages such as webpack-isomorphic-tools or universal-webpack or even the file-loader package that can emit or not the file, but I don't understand of to use it in my universal app.
I'm using file-loader with emitFile: false to exclude assets from bundling on server side. Works as expected.
const imageRules = (emit = true) => ({
test: /\.(png|svg|jpeg|jpg|gif|ico)$/,
type: "asset",
generator: {
emit: emit,
},
});
Then use it in webpack client config:
module: {
rules: [imageRules()],
},
And in server config
module: {
rules: [imageRules(false)],
},