How to use babel with webpack for ie11 compatibility - javascript

It's the first time i use webpack with babel, my goal is to make my small template app compatible with ie11.
For some reason I ignore, my JS does not work at all in ie11 even though I did set it as a target in my config. To test it, I use a ie11 on the internet but I don't have access to the stack errors since I'm on MacOS.
What am I missing here?
Source code for more info : https://github.com/VelynnXV/Front-End-Workflow
website : https://nifty-noether-cafbd5.netlify.app/
app.js
import regeneratorRuntime from "regenerator-runtime";
async function app() {
console.log('App entry point')
const template = document.getElementById('app')
await new Promise(r => setTimeout(() => r(), 2500))
template.innerHTML = `
<div class="web-container">
<div id="">
Async / awat test
</div>
</div>
`
console.log('App finished')
};
app();
webpack.config.json
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: ['core-js/stable', './src/app.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'app.js',
},
devServer: {
publicPath: "./src/",
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
},
plugins: [
new HtmlWebpackPlugin({ // will generate the html file WITH app.js
// see plugin here : https://webpack.js.org/plugins/html-webpack-plugin/
template: './src/index.html',
filename: './index.html'
})
],
module: {
rules: [ // set of rules letting webpack know how to handle .xyz files
{
test: /\.m?js$/, // source: https://webpack.js.org/loaders/babel-loader/
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
}
],
},
};
babel.config.js
// babel.config.js
module.exports = api => {
return {
plugins: [
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-transform-runtime",
],
presets: [
[
"#babel/preset-env",
{
useBuiltIns: "entry",
corejs:3,
// caller.target will be the same as the target option from webpack
targets: api.caller(caller => caller && caller.target === "node")
? { node: "current" }
: { chrome: "58", ie: "11" }
}
]
]
}
}
package.json
{
"name": "front-end-workflow",
"version": "1.0.0",
"description": "",
"main": "src/app.js",
"scripts": {
"dev": "npm run clean && npm run build && webpack serve",
"build": "webpack",
"clean": "rimraf ./dist"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.17",
"#babel/plugin-transform-runtime": "^7.12.17",
"#babel/preset-env": "^7.12.17",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^2.1.0",
"html-webpack-plugin": "^5.2.0",
"sass": "^1.32.8",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.23.0",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"#babel/runtime": "^7.6.3",
"core-js": "^3.3.2"
}
}

You almost have a complete configuration for IE11 support. The only thing you're missing is a target: "es5" option in your webpack configuration. Babel correctly transpiled your files. Webpack also injected all the necessary polyfills. However, you need to tell Webpack when it bundles the code together to use a syntax that your target browser can understand. For whatever reason, Webpack set the default to a version of ES that contained arrow functions. The error that IE11 console was showing (SCRIPT1002:syntax error) was pointing at the very first occurrence of an arrow function in your bundled app.js file.
An extra tip: use comments: false in your babel config to strip the code comments out of your bundle. This can slightly decrease the size of your bundle.
You can git apply this diff in your repo to take the changes in.
diff --git a/babel.config.js b/babel.config.js
index 8d2442b..273176c 100644
--- a/babel.config.js
+++ b/babel.config.js
## -2,6 +2,7 ##
module.exports = api => {
return {
+ comments: false,
plugins: [
"#babel/plugin-transform-runtime",
],
diff --git a/webpack.config.js b/webpack.config.js
index 2243a11..08af521 100644
--- a/webpack.config.js
+++ b/webpack.config.js
## -21,6 +21,7 ## module.exports = {
filename: './index.html'
})
],
+ target: "es5",
module: {
rules: [ // set of rules letting webpack know how to handle .xyz files using loader
// see loaders : https://webpack.js.org/loaders/

Related

Webpack 4 basic React js hello world fails with "Module parse failed: Unexpected token"

Update:
Code pushed to https://github.com/gsouvik/react_spa_experiment
Initial Post:
I know there are hundreds of threads out there, some had typos in webpack config, some used the loaders in a wrong way, some got it solved, some still open. But after numerous tries I still cannot get this working, a simple "Hello World" using Webpack 4, React js.
What I did
I was following this video tutorial line by line:
React & Webpack 4 from scratch
My package.json
{
"name": "my_react_experiment_2",
"version": "1.0.0",
"description": "Basic react with webpack ",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development --hot",
"build": "webpack --mode production"
},
"author": "Souvik Ghosh",
"license": "ISC",
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
My webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.export = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};
My .babelrc
{
"presets": ["env", "react"]
}
My directory structure
Expected behaviour
I fire up the dev server npm run dev. Expected to see my shiny new React js page saying "My first React Webpack project" (from the component /components/App.js)
Actual Behavior
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from "./components/App";
|
ReactDOM.render(, document.getElementById('root'));
| //ReactDOM.render('Hello User ', document.getElementById('root'));
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src main2
If required I can share the codebase via a git repo. Any help is greatly appreciated.
The issue is with typo in your webpack config file.
You have module.export which is not correct. It should be module.exports
Working example
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};

React hydrate TypeError: __webpack_require__.i(...) is not a function

I am getting a webpack TypeError when trying to use hydrate() in index.js. The error is not seen when I use ReactDOM.render() instead of hydrate and I am using hydrate for server side rendering.
src/index.js
import React from 'react';
import ReactDOM, { hydrate } from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store/configureStore';
hydrate(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
config/webpack.config.dev.js
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Errors should be considered fatal in development
require.resolve('react-error-overlay'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
// ** ADDING/UPDATING LOADERS **
// The "file" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "file" loader.
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "file" loader exclusion list.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
package.json
{
"name": "tratoli_backend",
"version": "0.1.0",
"private": true,
"dependencies": {
"autoprefixer": "7.1.1",
"babel-core": "6.25.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.0.0",
"babel-preset-react-app": "^3.0.1",
"babel-runtime": "6.23.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.4",
"dotenv": "4.0.0",
"eslint": "3.19.0",
"eslint-config-react-app": "^1.0.5",
"eslint-loader": "1.7.1",
"eslint-plugin-flowtype": "2.34.0",
"eslint-plugin-import": "2.2.0",
"eslint-plugin-jsx-a11y": "5.0.3",
"eslint-plugin-react": "7.1.0",
"express": "^4.16.2",
"extract-text-webpack-plugin": "2.1.2",
"file-loader": "0.11.2",
"fixed-data-table": "^0.6.4",
"fixed-data-table-2": "^0.7.17",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"isomorphic-fetch": "^2.2.1",
"jest": "20.0.4",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.0.0",
"postcss-loader": "2.0.6",
"promise": "7.1.1",
"react": "^15.6.1",
"react-bootstrap": "^0.31.2",
"react-dev-utils": "^3.0.2",
"react-dom": "^15.6.1",
"react-error-overlay": "^1.0.9",
"react-redux": "^5.0.5",
"react-router": "^4.2.0",
"react-router-dom": "^4.1.2",
"react-router-redux": "next",
"react-select": "^1.0.0-rc.5",
"react-table": "^6.8.0",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0",
"style-loader": "0.18.2",
"sw-precache-webpack-plugin": "0.11.3",
"url-loader": "0.5.9",
"webpack": "2.6.1",
"webpack-dev-server": "2.5.0",
"webpack-manifest-plugin": "1.1.0",
"webpack-node-externals": "^1.6.0",
"whatwg-fetch": "2.0.3"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js && npm run ssr",
"test": "node scripts/test.js --env=jsdom",
"start-ssr": "NODE_ENV=production webpack --config ./config/webpack.ssr.config.js",
"ssr": "NODE_ENV=production babel-node server/index.js --presets es2015,stage-2",
"ssr-start": "NODE_ENV=production node dist/server.js"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx"
]
},
"babel": {
"plugins": [
"css-modules-transform"
],
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-css-modules-transform": "^1.5.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-2": "^6.24.1"
}
}
And this here is the screenshot of the error message I received.
hydrate method is available in React 16(react-dom v16).
You are trying to access it from React 15(react-dom v15.6.1). This method is not available in React 15.
Update your react-dom to version to 16 and it should work fine.

Cannot find module "bundle.js"

I have a strange problem.... (Please, ignore my bad English :v)
I'm making app using HTML/CSS and js with jQuery. I'm using webpack too. I was using webpack-dev-server command since today - everything was working perfect. I wanted to generate single file - "bundle.js" without using server, cause i wanted to open app at another pc, without webpack.
That's how game looks like when it works
When I changed config in package.json from:
"start": "webpack-dev-server ./src/scrable.js"
To:
"start": "webpack ./src/scrable.js ./bundle.js"
I don't have any errors in my CMD console, when I typed "npm start".
But, when I opened my index.html file I saw in "source" mode that I have one error, which means that browser 'Cannot find module "bundle.js"'.
App is working, but not like it should - elements react for clicks, they're running some functions, but... just look at this:
That's how game looks like when it doesn't work
Do you have any ideas?
This is my package.json file
{
"name": "jstest_",
"version": "1.0.0",
"description": "",
"main": "scrable.js",
"scripts": {
"start": "webpack ./src/scrable.js ./bundle.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.28.0",
"style-loader": "^0.16.1",
"webpack": "^2.3.2",
"webpack-dev-server": "^2.4.2"
}
}
And this is my webpack.config.js file
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./src/scrable.js",
output: {
path: __dirname,
filename: "bundle.js",
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
module: {
loaders: [
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
}
};

webpack 2: ERROR in ./public/bundle.js from UglifyJs Unexpected character '`'

I got 2 related issues:
First: when I run npm run build the bundle.js file is not minified but I do get a bundle.js.map file.
Second: when I run webpack -d I only get a minified bundle.js file (and no error) but when I run webpack -p then I get a bundle.js that is not minified, a bundle.js.map, and those errors:
ERROR in ./public/bundle.js from UglifyJs
Unexpected character '`' [./app/config.js:5,0][./public/bundle.js:76,14]
ERROR in ./public/bundle.js from UglifyJs
Unexpected character '`' [./app/config.js:5,0][./public/bundle.js:76,14]
My question(s):
shouldn't the behaviors of webpack -p and webpack -d be the
opposite?
why is bundle.js not minified when I run npm run build?
why do I get those Unexpected character errors when I use template strings in my modules?
package.json looks like that:
{
...,
"scripts": {
"build": "webpack --progress --watch"
},
"devDependencies": {
"babel-core": "^6.13.2",
"babel-loader": "^6.2.5",
"babel-preset-es2015-native-modules": "^6.9.4",
"eslint": "^3.3.1",
"eslint-config-airbnb": "^10.0.1",
"eslint-plugin-html": "^1.5.2",
"eslint-plugin-import": "^1.13.0",
"eslint-plugin-jsx-a11y": "^2.1.0",
"eslint-plugin-react": "^6.1.2",
"webpack": "^2.1.0-beta.21"
}
}
while webpack.config.js is like that:
const webpack = require('webpack'); // eslint-disable-line import/no-extraneous-dependencies
const nodeEnv = process.env.NODE_ENV || 'production';
module.exports = {
entry: {
filename: './app/app.js'
},
output: {
filename: './public/bundle.js'
},
modules: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015-native-modules']
}
}
]
},
devtool: 'source-map',
plugins: [
// uglify
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
output: { comments: false },
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
})
]
};
I did search both here and Google (and webpack docs…) but I can't find anything useful to me. Thanks!!
UglifyJS2 does not have ES6/Harmony support in its releases yet. However, there's the Harmony branch which allows you to minify/uglify files with ES6 syntax.
I can suggest you an alternative solution which could help you spend less build time to transpile all ES6 to ES5.
Simply specify UglifyJs in your package.json, and let npm handles the dependencies.
"uglify-js": "git://github.com/mishoo/UglifyJS2#harmony-v2.8.22",

Webpack Missing Module 'Module Not Found'

I'm currently working on a react webpack babel etc site and trying to build the first time. The build is successful, but when I open up the browser I get the following error:
Uncaught Error: Cannot find module "/Users/michael.nakayama/Documents/Development/jamsesh/node_modules/webpack/node_modules/node-libs-browser/node_modules/process/browser.js"
This module exists. Going to that actual url in my browser shows the file in question. But I cannot figure out why webpack cannot find it. I don't know if this is a babel6 issue or a webpack issue, or neither. My config file looks like this:
var webpack = require('webpack');
var cleanWebpack = require('clean-webpack-plugin');
var ignore = new webpack.IgnorePlugin(new RegExp("/(node_modules|ckeditor)/"))
module.exports = {
devtool: 'inline-source-map',
entry: './lib/client/entry',
output: {
path: __dirname + '/public/js',
filename: 'app.js',
publicPath: 'http://localhost:8081/js/',
},
plugins: [
ignore,
],
resolve: {
extensions: ['', '.js'],
moduleDirectories: ['./node_modules']
},
module: {
loaders: [
{
test: /\.js?$/,
loaders: ['babel-loader?presets[]=react,presets[]=es2015,plugins[]=transform-es2015-classes,plugins[]=transform-react-jsx'],
exclude: /(node_modules)/,
}
]
}
}
and my webpack server file is as follows:
var WebpackDevServer = require('webpack-dev-server');
var webpack = require('webpack');
var config = require('../../webpack.config');
var server = new WebpackDevServer(webpack(config), {
// webpack-dev-server options
publicPath: config.output.publicPath,
stats: { colors: true },
});
server.listen(8081, 'localhost', function() {});
and here are the packages I have installed:
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.26",
"babel-loader": "^6.2.0",
"babel-plugin-syntax-jsx": "^6.3.13",
"babel-plugin-transform-es2015-classes": "^6.4.0",
"babel-plugin-transform-react-jsx": "^6.3.13",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"body-parser": "^1.14.2",
"clean-webpack-plugin": "^0.1.5",
"express": "^4.13.3",
"history": "^1.17.0",
"jade": "^1.11.0",
"nodemon": "^1.8.1",
"path": "^0.12.7",
"pg": "^4.4.3",
"react": "^0.14.6",
"react-dom": "^0.14.3",
"react-hot-loader": "^1.3.0",
"react-router": "^1.0.3",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
}
entry.js:
var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var routes = require('../routes');
// -v x.13.x
/**Router.run(routes, Router.HistoryLocation, function (Handler, state) {
React.render(<Handler/>, document.getElementById('react-app'));
});**/
var node = document.getElementById('react-app');
// -v 1.0.0
ReactDOM.render(<Router history={createBrowserHistory()} routes={routes}/> , node);
Also as a heads up, I have tried uninstalling and reinstalling all my packages. I have tried installing specifically the node-libs-browser modules. thanks.
The problem with ignore plugin on node_modules. In webpack.config.js, you have:
var ignore = new webpack.IgnorePlugin(new RegExp("/(node_modules|ckeditor)/"))
...
plugins: [
ignore,
],
From Ignore Plugin documentation:
Don’t generate modules for requests matching the provided RegExp.
Webpack tries to require module with the name node_modules/process/browser for React module and fails with it because it is ignored.
Try to remove node_modules from Ignore Plugin or write less global condition if you really need this.
Importing nodeExternals worked for me.
import nodeExternals from 'webpack-node-externals';
this is my server.webpack.config:
import path from 'path';
import nodeExternals from 'webpack-node-externals'; // changes
const CONTEXT = path.join( __dirname, "../.." ),
INPUT_SERVER_DIR = path.join( CONTEXT, "server" ),
OUTPUT_SERVER_DIR = path.join( CONTEXT, "dist/server" );
export default [
{
name: 'server',
target: 'node',
context: INPUT_SERVER_DIR,
node: {
__dirname: false
},
entry: './server',
devtool : 'source-map',
output: {
path: OUTPUT_SERVER_DIR,
filename: "server.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
resolve: {
extensions: ['.js']
},
**externals : [ nodeExternals() ]**
}
];

Categories