Webpack Karma cannot resolve local import - karma-runner

I am using Webpack for both the app and tests (using https://github.com/webpack/karma-webpack for it). The app is in typescript and the tests in Babel.
Importing something from a standalone module in the tests works (using import { cleanHTML, fromHTML, toHTML } from "../../app/utils/text.ts";, ie I need to mention the .ts extension otherwise it fails).
When I actually try to import a React component that imports a component in another file, I get the following error:
Module not found: Error: Cannot resolve 'file' or 'directory' ./blocks/paragraph.
The tree of directory looks like:
src/
app/
components/
blocks/
paragraph.ts
main.ts
tests/
components/
main_tests.js
utils/
And the main.ts imports paragraph.ts like so import { ParagraphBlockComponent } from "./blocks/paragraph";
Normal compilation works but not the tests.
Here is the karma config:
var path = require('path');
module.exports = function (config) {
config.set({
basePath: 'src',
singleRun: true,
frameworks: ['mocha', 'chai'],
reporters: ['dots'],
browsers: ['Firefox'],
files: [
'tests/index.js'
],
preprocessors: {
'tests/index.js': ['webpack']
},
webpack: {
noInfo: true,
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader']
},
{
test: /\_tests.js$/,
loaders: ['babel-loader']
}
]
}
},
webpackMiddleware: {
noInfo: true,
stats: {
color: true,
chunkModules: false,
modules: false
}
}
});
};
Did I miss something?

Adding the following to the karma webpack config fixed it for me
resolve: {
extensions: ['', '.js', '.ts']
},

Related

Babelrc configuration for IE11 support

I am trying to configure .babelrc for my react project but, cant make it work in IE11.
Can someone take a look at my configuration and see if there are things that I am missing, please?
[.babelrc]
{
"presets": [
"#babel/preset-env",
[
"#babel/preset-react",
{
"useBuiltIns": "usage",
"corejs": 3.26
}
]
],
"plugins": ["#babel/plugin-transform-runtime"]
}
[webpack.common.config.js]
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
module.exports = {
// Default. Can be erased for code simplification
entry: "./src/index.js",
output: {
filename: "[name].[contenthash].js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /[\\/]node_modules[\\/]/,
use: {
loader: "babel-loader",
},
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.html"),
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
}),
],
};
I have tried a lot of things(workarounds), but nothing seems to work.
The order of presets, importing core-js at the top of index.js file...

How to make rollup expand `require` statements?

I'm trying to wrap my head around rollup.
I'm using a library that generates a file with this format: IIFE with a require statement. For example
// index.js
(function() {
const myThing = require('./thing');
})()
//thing.js
module.exports = { a: 3 };
I'm trying to use rollup with a bunch of other things, but my bundle.js ends up looking like this:
(function () {
var myThing = require('./thing');
})();
What do I need to do so that my bundle.js ends up looking like this?:
(function () {
var myThing = { a: 3 };
})();
In case there is a problem with my setup, here is the rollup.config.js that I'm using:
var babel = require('rollup-plugin-babel');
export default {
input: 'index.js',
output: {
file: 'dist/bundle.js',
format: 'es'
},
plugins: [
babel({
exclude: 'node_modules/**'
})
]
};
These are the packages I have installed:
"babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.6.1",
"rollup": "^0.58.2",
"rollup-plugin-babel": "^3.0.4"
And my babel config:
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}
To build, I'm just calling rollup -c.
Okay, I figured it out. All I had to use was use the CommonJS plugin:
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
export default {
input: 'index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
resolve(),
commonjs(),
babel({
exclude: 'node_modules/**'
})
]
};

how to integrate ReactJs with Spring MVC in eclipse

I am a new to ReactJS, before I used angularJS for my client side. But now I want to integrate it with the present application on SpringMVC. Now I want to integrate ReactJS as client side instead of angularJS, please help me. If there is any example please help. I am using eclipse ide.
Try to create a view(jsp/html/xhtml) and link the UI build output to that. you may use webpack as a build tool for UI(React) which will return bundle file.
Then it can be included to view using script tag. Please note you can use webpack-dev-server for UI development and try to use Proxy to consume the spring-mvc service. Its a recommended way. A folder containing all the JS under webapp can be used if your using Maven as build tool for java.
webpack reference : https://webpack.js.org/
Sample Webpack.config.js for reference.
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
main: './src/scripts/main.js',
engine: './src/scripts/engine/Engine.js',
debugger: './src/scripts/debug/Debugmain.js',
client: './src/scripts/clientcode/Client.js'
},
output: {
path: path.resolve('./dist/client'),
filename: '[name].js',
publicPath: '/dist/client/',
chunkFilename: '[name].js'
},
devtool: 'inline-sourcemap',
cache: true,
resolve: {
alias: { ByteBuffer: 'bytebuffer' }
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'react-hot-loader'
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
presets: ['react', 'es2015'],
compact: false
}
},
{
enforce: 'pre',
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: [path.join(__dirname, './src', 'scripts')],
loader: 'eslint-loader'
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
loader: 'css-loader?sourceMap!less-loader?sourceMap'
})
},
{
test: /\.(eot|woff|woff2|ttf|otf|png|jpg)$/,
loader: 'file-loader?name=images/[name].[ext]'
}
]
},
devServer: {
port: 8080,
stats: 'errors-only',
proxy: {
'/api': {
target: 'http://localhost:20404', //http://localhost:20403/',
secure: false
}
},
historyApiFallback: {
index: 'debug.html'
}
},
plugins: [
new ExtractTextPlugin({
filename: './styles/main.css',
allChunks: true
})
],
resolve: {
modules: ['src/scripts', 'node_modules'],
extensions: ['.jsx', '.js'],
unsafeCache: true,
alias: {
components: path.resolve(__dirname, 'src', 'scripts', 'components'),
routes: path.resolve(__dirname, '.', 'routes'),
draggable_tab: path.resolve(__dirname, 'src', 'scripts', 'lib'),
utils: path.resolve(__dirname, 'src', 'scripts', 'utils'),
engine: path.resolve(__dirname, 'src', 'scripts', 'engine')
}
}
};

Karma debugging in Chrome no longer working

We are working on an Angular project where we are using Karma/Jasmine for our testing environment. We've been using the karma-chrome-launcher for debugging the tests and it was working great. For some reason, it has stopped working lately. I can't figure out why though, as we haven't changed anything regarding that pipeline. We tried updating to latest Karma (1.4.1), but that didn't help. Has anyone else seen this issue and been able to fix it? Help is appreciated. I've attached two images of what the Chrome inspector looks like when you first open the debugger and then after setting a breakpoint and hitting Refresh (it should look the same as the 1st image, but doesn't) edit: karma.config at bottom as well
'use strict';
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var patterns = wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js')
])
.concat(pathSrcHtml)
.concat('karmaMobileFramework/*.js');
var files = patterns.map(function(pattern) {
return {
pattern: pattern
};
});
files.push({
pattern: path.join(conf.paths.src, '/assets/**/*'),
included: false,
served: true,
watched: false
});
return files;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
singleRun: false,
autoWatch: true,
preprocessors : {
'/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'directive-templates'
},
logLevel: 'WARN',
frameworks: ['jasmine', 'jasmine-matchers', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-angular-filesort',
'karma-coverage',
'karma-jasmine',
'karma-jasmine-matchers',
'karma-ng-html2js-preprocessor',
'karma-htmlfile-reporter',
'karma-junit-reporter'
],
coverageReporter: {
type : 'html',
dir : 'reports/coverage/',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: 'report-jenkins' }
]
},
reporters: ['progress', 'html', 'junit'],
junitReporter: {
outputDir: 'reports/tests/',
outputFile: 'test-results.xml',
useBrowserName: false
},
htmlReporter: {
outputFile: 'reports/tests/results.html',
pageTitle: 'BOLT Unit Tests'
},
proxies: {
'/assets/': path.join('/base/', conf.paths.src, '/assets/')
}
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor is added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
config.set(configuration);
};

Can't set breakpoint in Chrome with Babel and Webpack

I have started a new project using the "new" stack: React+Webpack+Babel.
I am trying to explore of this work, and I am facing an issue with debugging in chrome. I can't set breakpoints on some lines in source files when I use Babel and Webpack. (I create sourcemaps).
I would like to be able to debug JSX files.
I have set a little project to reproduce the problem.
https://github.com/pierre-hilt/babel_webpack_sourcemap.git
Here is my configuration:
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'source-map',
entry: './build/index',
output: {
path: path.join(__dirname, 'static'),
filename: '[name].bundle.js',
publicPath: '/',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: "source-map-loader"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
}
babelrc:
{
"presets": [
"es2015",
"react"
],
"plugins": []
}
App.jsx (I try to break on line 6 but it is impossible...)
import React, { Component, PropTypes } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: props.title,
};
}
changeTitle(newTitle) {
this.setState({ title: newTitle });
}
render() {
return (
<div>
This is {this.state.title}
</div>
);
}
}
App.propTypes = { title: PropTypes.string };
export default App;
I tried different devtool options (cheap, module, ...).
I also tried Babel loader, but is does not work either.
Do you have any idea? Is it a known issue?
OK, I found a workaround that works fine!
babelrc
{
"presets": [
"react"
],
"plugins": []
}
Babel script
"babel": "babel client -d build --source-maps",
webpack config
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'source-map',
entry: './build/index',
output: {
path: path.join(__dirname, 'static'),
filename: '[name].bundle.js',
publicPath: '/',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: "source-map-loader"
}
],
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
}
I first transpile JSX with babel only, then I transpile ES2015 with babel loader and webpack.
At the end I got source files where I can set break points anywhere!