Webpack setup to bypass loading specific files with babel - reactjs

I have a bootstrap theme that came with JS and CSS files that I'd like to integrate into my react app. I'm running into issues requiring the JS files because they don't export modules appropriately or properly define variables (using babel loader). I'd like to be able to require the JS in my app but not run them through babel. I'd also like to be able to use webpack's chunking and minification on these files if possible.
How do I go about setting this up?
Edit
I'm pretty sure what I need in reference to babel is the exclude config parameter. Unfortunately no matter what I try the exclude config isn't honored.
{
test: /\.js/,
loaders: [ 'react-hot', 'babel' ],
include: [
path.join(__dirname, 'src', 'app')
],
exclude: [
path.join(__dirname, 'src', 'semantic-v1.1.2')
]
},
Here's the error I receive:
ERROR in ./src/semantic-v1.1.2/assets/js/imagesloaded.pkgd.js
Module not found: Error: Cannot resolve module 'eventEmitter' in /Users/bradr/Dropbox (Personal)/Development/ritasfoods-com/src/semantic-v1.1.2/assets/js
# ./src/semantic-v1.1.2/assets/js/imagesloaded.pkgd.js 731:2-735:24
I'm sure I'm missing something simple.
Full webpack.config.js:
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/app/index'
],
output: {
path: path.join(__dirname, 'static'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
noParse: [
/aws\-sdk/, // Hack to be able to import aws sdk.
],
loaders: [
{
test: /\.js/,
loaders: [ 'react-hot', 'babel' ],
include: path.join(__dirname, 'src/app'),
exclude: path.resolve('src', 'semantic-v1.1.2')
},
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.md$/, loader: "html!markdown?gfm=false" },
{ test: /\.html/, loader: 'html' },
{ test: /\.yaml/, loader: 'json!yaml' },
{ test: /\.(woff|woff2)$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf$/, loader: "file-loader" },
{ test: /\.eot$/, loader: "file-loader" },
{ test: /\.svg$/, loader: "file-loader" },
{ test: /\.(jpg|png)$/, loader: 'url' }
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
resolve: {
// Removes the need to specify file type in imports.
extensions: ['', '.js', '.json'],
alias:{
theme: path.resolve( __dirname, 'src', 'semantic-v1.1.2', 'assets')
}
}
};
.babelrc
{
"presets": ["es2015", "stage-0", "react"],
}
package.json
{
"name": "ritasfoods-com",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": true,
"scripts": {
"start": "node server.js",
"build-prod": "./node_modules/webpack/bin/webpack.js -p --config webpack.config.prod.js --progress --colors",
"deploy-prod": "ops/deploy-prod"
},
"repository": {
"type": "git",
"url": "..."
},
"author": "Brad Reynolds",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.6.0",
"babel-loader": "^6.2.4",
"babel-plugin-transform-class-properties": "^6.6.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.23.1",
"html-loader": "^0.4.3",
"node-sass": "^3.4.2",
"react-hot-loader": "^1.3.0",
"redux-devtools": "^3.2.0",
"redux-devtools-dock-monitor": "^1.1.1",
"redux-devtools-log-monitor": "^1.0.11",
"sass-loader": "^3.1.2",
"style-loader": "^0.13.1",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"aws-sdk": "^2.2.40",
"babel-polyfill": "^6.8.0",
"babel-preset-stage-0": "^6.5.0",
"es6-promise": "^3.1.2",
"events": "^1.1.0",
"exports-loader": "^0.6.3",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.8.5",
"html-loader": "^0.4.3",
"imports-loader": "^0.6.5",
"invariant": "^2.2.1",
"jquery": "^2.2.1",
"less": "^2.6.1",
"less-loader": "^2.2.3",
"markdown-loader": "^0.1.7",
"mustache": "^2.2.1",
"numeral": "^1.5.3",
"pluralize": "^1.2.1",
"react": "15.0.1",
"react-dom": "15.0.1",
"react-redux": "^4.4.5",
"react-router": "^2.0.0",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.0.1",
"url-loader": "^0.5.7"
}
}
server.js
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config.js');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(8080, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:8080/');
});

I bit the bullet and installed every JS file from the bootstrap theme via npm. It was a PITA as I had to configure a few via webpack. But it's done so I can move on.

I do this for image assets for a chrome extension. The app itself doesn't use them, but Chrome does, so I need them copied into the build folder.
Create an extra entry for static files. Your entry is a js file that just requires all the static files. You will end up with a useless extra bundle as a byproduct, but all your files will be copied over to your build folder.
I'll show you the example of images first because I have working code to pull that from.
webpackconfig.js
// ...
entry: {
// ...
'img': './img/index.js'
},
output: {
// dynamic bundle name for multiple outputs
filename: '[name].js'
// ...
},
rules: {
// ...
{
test: /\.png|svg|jpg|gif$/,
use: [
{
// copy loaded files to
// output_base_path/input_relative_path/filename.extension
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
useRelative: true
}
},
{
loader: 'image-webpack-loader',
options: { /* ... */ }
}
]
}
}
src/img/index.js
// This is the only line in this file.
// Recursively require all png or jpg from current folder
require.context('./', true, /\.(png|jpg)$/)
So now I'll get speculative and try to translate it to your use-case as best I can without being able to test it:
webpackconfig.js
// ...
entry: {
// ...
'static': './static/index.js'
},
output: {
filename: '[name].js'
// ...
},
rules: {
// ...
{
// I'm guessing the string being tested here is a relative path.
// If I'm wrong, this regex will need some tweaking.
// Matches everything in assets folder
test: /^assets\/.+/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
useRelative: true
}
},
{
// Not sure if you actually need this loader, but it's something I
// would try if file loader is choking on your files, especially
// if you are processing multiple filetypes.
loader: 'raw-loader'
}
]
}
}
src/assets/index.js
// Let's just match everything. Putting images in this folder will
// probably give you headaches. Limit it to text files and handle images
// separately.
require.context('./', true, /.+/)
Here's some info on require.context and file-loader

Related

Error while configuring webpack 4 in my react (create-react-app) project

i am configuring the webpack 4 in my react project (create-react-app)
i have installed all the require loaders/file to configure my webpack, but there is always some different error, (some time its about sass-loader/css-loader/style-loader)
Now am dealing with (eot,woff,woff2,ttf) files error.
i don't know, i am conflicting the versions of node-sass/webpack/loaders or what.
please help me to configuring webpack in my project.
i am attaching the configuration files and errors screen.
Here is my devdependencies in my package-json file.
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"babel-loader": "^8.2.5",
"css-loader": "^3.6.0",
"file-loader": "^6.2.0",
"laravel-echo": "^1.11.2",
"less": "^4.1.2",
"less-loader": "^5.0.0",
"node-sass": "^4.14.1",
"pusher-js": "^7.0.3",
"raw-loader": "^4.0.2",
"react-error-overlay": "6.0.9",
"sass": "^1.51.0",
"sass-loader": "^7.1.0",
"style-loader": "^1.3.0",
"ts-loader": "^9.2.8",
"url-loader": "^4.1.1",
"webpack": "^4.42.0",
"webpack-cli": "^4.9.2"
}
webpack.config.js file
const path = require("path");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
publicPath: "/dist/",
},
// ...add the babel-loader and preset
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
// {
// test: /\.(scss|css|sass)$/,
// use: ["sass-loader", "style-loader", "css-loader"],
// },
{
test: /\.(scss|css|sass)$/,
use: [
// style-loader
{
loader: "style-loader",
},
// css-loader
{
loader: "css-loader",
options: {
modules: true,
},
},
// sass-loader
{
loader: "sass-loader",
options: {
modules: true,
},
},
],
},
{
test: /\.(woff2|woff|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
// options: {
// name: "[name].[ext]",
// outputPath: "fonts/",
// },
},
],
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: "file-loader",
},
],
},
],
},
// ...add resolve to .jsx extension
resolve: {
extensions: ["*", ".js", ".jsx"],
},
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Kindly check your themes scss and comment imports one by one and try to make build. In my case scss files were causing issues.

babel core 7.4.4, using all polyfills by default

I was tasked to make one of the mobile apps written in react compatible with opera mini in extreme mode. During the testing, I learned that nothing that is in react code works there, however by including this babel-polyfill before main.js file it actually is working.
I tried to include it to a Webpack so the code is actually converted instead of including a huge library but without success.
package.json file
"devDependencies": {
"#babel/core": "^7.4.4",
"#babel/plugin-proposal-class-properties": "^7.10.1",
"autoprefixer": "^8.6.3",
"babel-loader": "^8.0.6",
"copy-webpack-plugin": "latest",
"css-loader": "latest",
"file-loader": "latest",
"html-webpack-plugin": "latest",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "latest",
"postcss-loader": "latest",
"sass-loader": "latest",
"style-loader": "latest",
"url-loader": "latest",
"webpack": "latest",
"webpack-cli": "latest",
"webpack-dev-server": "latest"
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0"
}
.babelrc file:
{
"presets": ["#babel/env", "#babel/react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.js file:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html",
});
module.exports = {
output: {
publicPath: "/",
filename: "js/main.[hash:8].js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.(png|jpg|gif|ico|svg|eot|ttf|woff|woff2)$/,
loader: "url-loader",
options: {
limit: 25000,
outputPath: "assets/",
name: "[name].[hash:8].[ext]",
},
},
{
test: /\.(scss|sass|css)$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
resolve: {
extensions: [".js", ".jsx", ".json"],
},
plugins: [
htmlPlugin,
new MiniCssExtractPlugin({
filename: "css/style.[hash:8].css",
}),
],
devServer: {
historyApiFallback: {
rewrites: [{ from: /^\/$/, to: "/index.html" }],
},
},
};
How these can be modified so I don't have to include entire babel-polyfill.min.js and Webpack + babel will actually convert the code to work?
--EDIT
I had success with following changes:
package.json file
...
"browserslist": [
"dead"
],
...
.babelrc file:
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": 3
}
],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
[
"#babel/transform-runtime",
{
"corejs": 3
}
]
]
}
webpack.config.js file:
...
entry: "./src/index.js",
...
Once this setup is in place, i have to manually include import "core-js"; at the top of every file that is part of project so for example:
index.js
App.js
components/events.jsx
components/popup.jsx
and so on...
is there a way to avoid that inclusion by some configuration in webpack or babel ? (i tried "useBuiltIns": "usage" instead of entry but it doesnt include all needed polyfills)
I was gonna suggest you drop babel-polyfill since it's deprecated as of 7.4.0 but then saw your edit.
If you want to avoid importing core-js everywhere you should use "useBuiltIns": "usage".
I think the reason it doesn't polyfill everything is because your browserslist query doesn't match to opera mini according to (https://browserl.ist/?q=dead), you should specify it, something like:
...
"browserslist": [
"dead",
"op_mini all"
],
...

Bundle NPM package that connects to applications store

I've been fighting with webpack and loosing for the last day and a half and I give up, please help!
So what I'm trying to do is create an NPM package that will be used in many of our sites. We have multiple sites with a shared functionality, we are using redux and I have made an npm package that provides actions, reducers and middleware that can be imported across multiple projets. That works great, no worries there. I am now trying to make a second package that contains components that use the main application's state from the redux store.
This second package uses selectors and dispatches actions provided by the first package.
I wrote the component in the main application, works great,
I created a new project for the second package, copy and pasted the component, it's scss module file, added the first package and other dependancies as peer dependancies
built with webpack (after some troubles with peer dependancies not being found, I had to install them with install-peers, maybe this has something to do with my problem)
I then npm installed the package in the main application... and I'm getting "store is undefined".
I think there is a problem with my webpack config, somehow the component doesn't seem to have access to my application's store as if it exists in its own little world. This is my guess, I could be miles off.
We are using react, next, redux and scss modules.
Here is my webpack config (externals are commented out as I'm using peer-deps-externals-webpack-plugin):
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
var path = require("path");
var PeerDepsExternalsPlugin = require('peer-deps-externals-webpack-plugin');
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve("build"),
filename: "index.js",
// libraryTarget: "commonjs2",
library: 'mm-chat-components',
libraryTarget: 'umd',
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css',
chunkFilename: 'styles.css'
}),
new PeerDepsExternalsPlugin()
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.module\.s(a|c)ss$/,
loader: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: false
}
},
{
loader: 'sass-loader',
options: {
sourceMap: false
}
}
]
},
{
test: /\.s(a|c)ss$/,
exclude: /\.module.(s(a|c)ss)$/,
loader: [
'css-loader',
{
loader: 'sass-loader',
options: {
sourceMap: false
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
]
},
externals: {
// react: "react",
// reactDOM: 'react-dom',
// mmTheme: 'mm-theme',
// mmChatRedux: 'mm-chat-redux',
// mmReduxBase: 'mm-redux-base',
// redux: 'redux',
// reactRedux: 'react-redux',
// finalForm: 'final-form',
// reactFinalForm: 'react-final-form',
// twilioChat: 'twilio-chat'
}
};
Here is my package.json:
{
"name": "mm-chat-components",
"version": "1.0.0",
"description": "",
"main": "./build/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build-webpack": "webpack --mode production"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"mm-redux-base": "git+https://github.com/MMTSURVEY/mm-redux-base.git",
"mm-theme": "git+https://github.com/MMTSURVEY/mmj-theme.git",
"final-form": "^4.18.7",
"react-final-form": "^6.3.5",
"react": "^16.13.1",
"twilio-chat": "^3.3.7",
"react-redux": "^7.2.0",
"react-dom": "^16.12.0",
"mm-chat-redux": "git+https://github.com/MMTSURVEY/mm-chat-redux.git"
},
"devDependencies": {
"#babel/cli": "^7.0.0",
"#babel/core": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"babel-plugin-react-css-modules": "^5.2.6",
"babel-plugin-react-css-modules-sass": "^1.1.0",
"css-loader": "^3.5.3",
"install-peers": "^1.0.3",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.14.1",
"peer-deps-externals-webpack-plugin": "^1.0.4",
"sass-loader": "^8.0.2",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
}
}
And my babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
I'm generally lost when using webpack, it still seems like magic that's far beyond my comprehension.
That's lots of info, I hope it's all clear! Thanks in advance for any help! You guys rock.
Beau

ReactJS - Unexpected Token with 3 comma

Im tring to compile my react frontend app but I got a couple of error about "..." syntax:
ERROR in condition.jsx
Module build failed: SyntaxError: Unexpected token (25:10)
23 | show_table : undefined,
24 | fa_count : 0,
> 25 | ...this.state
| ^
26 | }
condition.jsx extends (with OOP) another component so I need ...this.state to merge parent state with the local state.
When launcing it with npm start, it works perfectly but the compiler seems doesn't want that syntax.
UPDATED:
This is my current webpack settings:
const webpack = require('webpack');
const path = require('path');
const Uglify = require("uglifyjs-webpack-plugin");
var plugins = [];
plugins.push(new Uglify());
var config = {
context: __dirname + '/src',
entry: {
javascript: "./index.js",
},
plugins: plugins,
output: {
path: path.join(__dirname,'../static/js/'),
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test:/\.(js|jsx)?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env','react']
}
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
]
},
}
module.exports = env => {
return config;
}
Lanching with this command:
./node_modules/.bin/webpack --config webpack.config.js
In a comment, you said that you don't have any babelrc. Then I already re-read the Webpack offical document and take this sample code from there for you:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
}
}
]
after installing the babel-plugin-transform-object-rest-spread package, you could follow this sample code to update your webpack config. Read more about it: Webpack Loader
This is the combination that works for me, I'm using the babel-preset-stage-2 instead.
In the webpack.config.js:
....
module: {
rules: [
{
test:/\.(js|jsx)?$/,
use: ['babel-loader']
},
....
]
}
....
I create a .babelrc file in the root folder and its content is:
{
"presets": ["env", "react", "stage-2"],
....
}
And this is my package.json file:
{
"name": "demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.9.0",
"react-hot-loader": "^4.3.3",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"webpack": "^4.15.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"uuid": "^3.3.2"
}
}
Hopefully, it works for you.
You didn't tell about your configuration. But I assume babel and webpack. This seems to be an issue with your babel config. Try this plugin:
https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread
After you've installed it, add
"plugins": ["transform-object-rest-spread"]
To your .babelrc file and run the webpack again.

React Jest - Unexpected token import

I'm learning react and I want to test one of my components but I'm stuck with this error:
{import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
Here's some things I have tried from reading post on stackoverflow and github
added test presets and these plugins "transform-es2015-modules-commonjs", dynamic-import-node" to my babel config
{
"presets": ["es2015", "react"],
"env": {
"test": {
"presets":[
["es2015", { "modules": false }],
"stage-0",
"react"],
"plugins": [
"transform-es2015-modules-commonjs",
"dynamic-import-node"
]
}
}
}
In my package.json the Jest property has these settings:
"jest": {
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"jsx",
"js"
],
"transform": {},
"moduleDirectories": [
"node_modules"
],
"transformIgnorePatterns": [
"node_modules/(?!react)/"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
},
My actual component is built with ES6 and typescript if that helps you help me :)
From what I have read, it seems jest chokes on import because node doesn't understand ES6 import. None of the solutions I have tried online have seemed to work.
Also here are my dev Dependencies:
"devDependencies": {
"awesome-typescript-loader": "^3.2.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.4",
"enzyme": "^2.9.1",
"eslint": "^4.4.1",
"eslint-config-airbnb": "^15.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.2.0",
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-harddisk-plugin": "^0.1.0",
"html-webpack-plugin": "^2.30.1",
"jest": "^20.0.4",
"node-sass": "^4.5.3",
"react-test-renderer": "^15.6.1",
"regenerator-runtime": "^0.10.5",
"sass-loader": "^6.0.6",
"source-map-loader": "^0.2.1",
"style-loader": "^0.18.2",
"ts-jest": "^20.0.10",
"typescript": "^2.4.2",
"webpack": "^3.5.1",
"webpack-dev-middleware": "^1.12.0",
"webpack-dev-server": "^2.7.0"
},
Webpack config
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const HOST = "127.0.0.1";
const PORT = "9000";
const devServerUrl = "http://localhost:" + PORT + "/";
const config = {
devtool: 'source-map',
context: __dirname, // `__dirname` is root of project and `src` is source
entry:
[
'./src/index.js',
'./src/ui/styles.scss'
],
output: {
path: path.join(__dirname, 'dist'),
filename: "bundle.js",
publicPath: ''
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css']
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
{ test: /\.js$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{ test: /\.jsx$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{
test: /\.(sass|scss)$/, use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
devServer: {
contentBase: "dist/",
noInfo: true,
inline: true,
compress: true,
port: PORT,
host: HOST,
hot: true
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html', // Output file name.
template: './public/index.html', // Use our HTML file as a template for the new one.
inject: 'body',
alwaysWriteToDisk: true,
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
}),
new ExtractTextPlugin({ // define where to save the file
filename: 'styles.bundle.css'}),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackHarddiskPlugin({
outputPath: path.resolve(__dirname, 'dist')
})
],
};
module.exports = config;
Thanks
Jest doesn't work with Typescript.
I have removed Jest from my project and installed Mocha, Karma, Chai & Enzyme.
Effortless to set up compared to Jest which masquerades as a:
Zero configuration testing platform
This article was a huge help: Getting Started on Testing with Typescript, ReactJS, and Webpack.
Hopefully this will save others from wasting their time getting Jest to work with Typescript.
It's because you have configured babel to not transpile ES6 modules
"presets":[
["es2015", { "modules": false }],
Try again with that modules to true (or omitted, since it defaults to true) and it should work.
you need to install babel to compile your es6 and react code
do it using
C:\Users\username\Desktop\reactApp>npm install babel-core
C:\Users\username\Desktop\reactApp>npm install babel-loader
C:\Users\username\Desktop\reactApp>npm install babel-preset-react
C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015
Try to keep our webpack as
var config = {
entry: './todoApp.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 9191
},
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;

Resources