Webpack config issue with loaders when running gulp serve or build - javascript

Am new to using webpack and used Fountain Web App to scaffold my setup and then adding in my own stuff. Am running into issues I am not sure what else to do with. I have searched and tried, but not sure if the issues are being caused by loaders or what.
When I run gulp serve or build, I get this:
C:\vapor\source\mgmtPortal\dashboard>gulp serve
[14:23:43] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\browsersync.js
[14:23:43] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\karma.js
[14:23:44] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\misc.js
[14:23:44] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\webpack.js
fallbackLoader option has been deprecated - replace with "fallback"
loader option has been deprecated - replace with "use"
[14:23:45] Using gulpfile C:\vapor\source\mgmtPortal\dashboard\gulpfile.js
[14:23:45] Starting 'serve'...
[14:23:45] Starting 'webpack:watch'...
[14:23:45] 'webpack:watch' errored after 121 ms
[14:23:45] WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'debug'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
The 'debug' property was removed in webpack 2.
Loaders should be updated to allow passing this option via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:
plugins: [
new webpack.LoaderOptionsPlugin({
debug: true
})
]
at webpack (C:\vapor\source\mgmtPortal\dashboard\node_modules\webpack\lib\webpack.js:19:9)
at webpackWrapper (C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\webpack.js:24:26)
at gulp.task.done (C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\webpack.js:15:3)
at taskWrapper (C:\vapor\source\mgmtPortal\dashboard\node_modules\undertaker\lib\set-task.js:13:15)
at taskWrapper (C:\vapor\source\mgmtPortal\dashboard\node_modules\undertaker\lib\set-task.js:13:15)
at taskWrapper (C:\vapor\source\mgmtPortal\dashboard\node_modules\undertaker\lib\set-task.js:13:15)
at bound (domain.js:280:14)
at runBound (domain.js:293:12)
at asyncRunner (C:\vapor\source\mgmtPortal\dashboard\node_modules\async-done\index.js:36:18)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
at Module.runMain (module.js:606:11)
at run (bootstrap_node.js:390:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:505:3
[14:23:45] 'serve' errored after 127 ms
My webpack config looks like this:
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
// const rules = {
// // ...
// componentStyles: {
// test: /\.scss$/,
// loaders: ["style-loader", "css-loader", "sass-loader"],
// exclude: path.resolve(__dirname, 'src/app')
// },
// fonts: {
// test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
// loader: 'file-loader?name=fonts/[name].[ext]'
// },
// // ...
// }
// const config = module.exports = {};
// config.module = {
// rules: [
// // ...
// rules.componentStyles,
// rules.fonts,
// // ...
// ]
// };
module.exports = {
module: {
// preLoaders: [{
// test: /\.js$/,
// exclude: /node_modules/,
// loader: 'eslint'
// }],
loaders: [{
test: /.json$/,
loaders: [
'json'
]
},
{
test: /\.(css|scss)$/,
loaders: [
'style',
'css',
'sass',
'postcss'
]
},
{
test: /.html$/,
loaders: [
'html'
]
}
]
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"Tether": "tether"
}),
new HtmlWebpackPlugin({
template: conf.path.src('index.html')
}),
new webpack.ProvidePlugin({ // inject ES5 modules as global vars
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Tether: 'tether'
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
conf.paths.src
)
],
postcss: () => [autoprefixer],
debug: true,
devtool: 'source-map',
output: {
path: path.join(process.cwd(), conf.paths.tmp),
filename: 'index.js'
},
entry: `./${conf.path.src('index')}`
};
Can any of you lend a hand with helping me on this?
Thanks much.

To resolve this specific error you need to remove debug: true, from your webpack config. The error is saying that the debug parameter is not valid for Webpack 2, and it was only valid in webpack 1.
The line of the error is here:
[14:23:45] WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'debug'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
The 'debug' property was removed in webpack 2.
It sounds like you upgraded to webpack 2, maybe unintentionally. If it was on purpose, you can view the migration guide here, on how to properly structure your configuration file. It likely needs more changed if you plan on staying with Webpack 2.
If it was unintentional, you can reinstall webpack by running the npm command, but it is not recommended and not supported anymore.
npm install --save webpack#1.15.0

Related

Webpack - Excluding node_modules with also keep a separated browser and server management

(webpack.config.js file content below)
I'm trying to make a webpack exclusion on node modules.
I found that using webpack-node-externals works for it but using that on my common config causes this other error:
Require is not defined on reflect-metadata - __webpack_require__ issue
So... I was wondering how can i exclude webpack bundling also on the browser side without getting any issue.
My webpack version: 3.11.0
webpack-config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
//externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: { modules: false },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '#ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder,
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
GOT IT!
Before posting my solution, I'd like to thanks Aluan Haddad for his useful comment in my question above.
As suggested by Aluan, in fact, the problem was related to the need to use also a module loader, more than a module bundler.
So, the steps that I followed are these:
Installing requireJS ==> http://requirejs.org/docs/node.html
Removing externals: [nodeExternals()], // in order to ignore all modules in node_modules folder from my common webpack configuration and adding it under my server configuration (done before my question, but it's a really important step) [see webpack.config.js content in the question]
Adding target: 'node', before my externals point above, under my server side section (done before my question, but it's a really important step) [see webpack.config.js content in the question]
This makes sure that browser side keeps target:'web' (default target), and target becomes node just for the server.
launched webpack config vendor command manually from powershell webpack --config webpack.config.vendor.js
launched webpack config command manually from powershell webpack --config webpack.config.js
That worked for me! Hope It will works also for anyone else reading this question and encountering this issue!

Build error while compiling create-react-app

I am new to Reactjs and am started learning it. I have been trying to start a basic hello world program but its failing at compilation level.
Created a start up hello-word program with create-react-app hello-world it gave me a nice folder structure with bunch of files.
And Here you can see the compilation error
Failed to compile
./src/index.js
Module build failed: Error: Failed to load plugin import: Cannot find module
'eslint-plugin-import'
Referenced from:
at Array.forEach (native)
at Array.reduceRight (native)
This error occurred during the build time and cannot be dismissed.
Here the error states cannot find module so i tried to install eslint plugin import ,standard ..etc but still its not worked.
Below is my webpack.config.dev.js
// #remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// #remove-on-eject-end
'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');
const env = getClientEnvironment(publicUrl);
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',
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// 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'),
// 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: {
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)
),
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// #remove-on-eject-begin
// Resolve Babel runtime relative to react-scripts.
// It usually still works on npm 3 without this but it would be
// unfortunate to rely on, as react-scripts could be symlinked,
// and thus babel-runtime might not be resolvable from the source.
'babel-runtime': path.dirname(
require.resolve('babel-runtime/package.json')
),
// #remove-on-eject-end
// 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/).
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
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,
eslintPath: require.resolve('eslint'),
// #remove-on-eject-begin
baseConfig: {
extends: [require.resolve('eslint-config-react-app')],
},
ignore: false,
useEslintrc: false,
// #remove-on-eject-end
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
{
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: {
// #remove-on-eject-begin
babelrc: false,
presets: [require.resolve('babel-preset-react-app')],
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
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',
}),
],
},
},
],
},
{
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file"
loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
],
},
plugins: [
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin(env.stringified),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
performance: {
hints: false,
},
};
Can any one guide me how to come out of this build error.
This means eslint-plugin-import not available in your node_modules.
A fresh npm install eslint-plugin-import and restart the application should fix this issue.
If that didn't fix, try upgrading your npm version:
npm install -g npm#latest
Finally issue got resolved after installing few below packages globally:
eslint-config-react-app
eslint
babel-eslint
eslint-plugin-react
eslint-plugin-import
eslint-plugin-jsx-a11y
eslint-plugin-flowtype
And deleted package.lock.json file then ran npm install
Finally npm start Its just worked. Thank you
Run this command:
"lint:fix": "eslint './src/**/*.{js,jsx}' --fix"
Then fixed all problems.
And Sure file ".eslint.js" has no any problem:
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
parserOptions: {
parser: "babel-eslint",
ecmaVersion: 2020,
sourceType: "module",
},
extends: ["plugin:react/recommended", "plugin:prettier/recommended"],
plugins: [],
rules: {
"react/prop-types": 0,
},
};

React webpack dev server works but when I create prod bundle I get reference error "require is not defined"

I am running a react project and have no problem testing with the local dev server, however as soon as I make a production webpack build and load the page in the browser I get a white screen and in console I see an error saying "Uncaught ReferenceError: require is not defined". When I look into the specific javascript it starts around require("url"), but I don't have any require("url") in any of my javascript source files, so it must be from a module.
Here is the part that the console points to when it throws the error (cleaned up as best as I can)
function(e,t){e.exports=require("url")},function(e,t,n){"use
strict";Object.defineProperty(t,"__esModule",
{value:!0}),t.default=function(e){var t=[];return
Object.keys(e).forEach(function(n){return
t.push(e[n])}),t}},function(e,t,n){"use strict";function a(e){return
Object.prototype.toString.call(e).slice(8,-1)}function r(e)
{return"Number"===a(e)&&!isNaN(e)&&e>0}function o(e){return
e.isRequired=function(t,n,a){if(void 0===t[n])return new Error("The
prop "+n+" is marked as required in \n "+a+", but its value is
undefined.");e(t,n,a)},e}Object.defineProperty(t,"__esModule",
{value:!0}),t.falseOrElement=t.falseOrNumber=void
0,t.typeOf=a,t.isValidDelay=r;var
i=n(0);t.falseOrNumber=o(function(e,t,n){var
a=e[t];return!1===a||r(a)?null:new Error(n+" expect "+t+" \n to
be a valid Number > 0 or equal to false. "+a+"
given.")}),t.falseOrElement=o(function(e,t,n){var
a=e[t];return!1===a||(0,i.isValidElement)(a)?null:new Error(n+"
expect "+t+" \n to be a valid react element or equal to false.
"+a+" given.")})}
Here is my webpack base/prod config:
//BASE CONFIG
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
target: 'node',
entry: './assets/js/index',
output: {
path: path.resolve('./assets/bundles/'),
publicPath: '/static/bundles/',
filename: "[name]-[hash].js"
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
], // add all common plugins here
module: {
rules: [
/* {
enforce: "pre",
test: /\.js$/,
loader: "eslint-loader",
exclude: /node_modules/
},*/
{test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
}, { test: /\.(scss|css)$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
}, {
test: /\.(jpg|png|gif)$/,
loaders: ['url-loader?limit=25000']
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
loader: 'file-loader?name=public/fonts/[name].[ext]'
},
],
},
resolve: {
//tells webpack where to look for modules
modules: [path.resolve(__dirname, "app"), "node_modules"],
//extensions that should be used to resolve modules
extensions: ['.js', '.jsx']
}
}
//PROD CONFIG
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
var config = require('./webconfig.base.js')
config.output.path = require('path').resolve('./assets/bundles')
config.plugins = config.plugins.concat([
new BundleTracker({filename: './webpack-stats-prod.json'}),
// removes a lot of debugging code in React
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}}),
// keeps hashes consistent between compilations
new webpack.optimize.OccurrenceOrderPlugin(),
// minifies your code
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
warnings: false
}
})
])
module.exports = config
use target: 'web' (or nothing), instead of target: node

Still getting 'Symbol' is undefined' error even after adding babel-polyfill in my webpack

https://babeljs.io/docs/usage/polyfill/#usage-in-browser
I did not understand the lines on the documentation page under:
Usage in Browser heading
can someone help me with what else is required:
Below are my code snippets:
I'm using storybook as a boilerplate:
webpack.config.js file:
entry: [
'babel-polyfill',
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs
]
index.js file:
import 'babel-polyfill';
import React from 'react';
Is there some other files also where I need to add babel-polyfill related code.
require('babel-polyfill');
var path = require('path');
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('./env');
var paths = require('./paths');
var publicPath = '/';
var publicUrl = '';
var env = getClientEnvironment(publicUrl);
module.exports = {
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill',
require.resolve('react-dev-utils/webpackHotDevClient'),
require.resolve('./polyfills'),
paths.appIndexJs
],
output: {
path: paths.appBuild,
pathinfo: true,
filename: 'static/js/bundle.js',
publicPath: publicPath
},
resolve: {
fallback: paths.nodePaths,
extensions: ['.js', '.json', '.jsx', ''],
alias: {
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc,
}],
loaders: [{
exclude: [/\.html$/, /\.(js|jsx)$/, /\.css$/, /\.json$/],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
query: {
cacheDirectory: true
}
}, {
test: /\.css$/,
loader: 'style!css?importLoaders=1!postcss'
}, {
test: /\.json$/,
loader: 'json'
}
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
new InterpolateHtmlPlugin({
PUBLIC_URL: publicUrl
}),
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new webpack.DefinePlugin(env),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(paths.appNodeModules)
],
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
There are two ways to get this code into your browser.
1 - Include the babel-polyfill module in the webpack bundle
2 - Load it as an external script in your html
Webpack - adding bundle dependencies with entry arrays
Put an array as the entry point to make the babel-polyfill module available to your bundle as an export.
With webpack.config.js, add babel-polyfill to your entry array.
The webpack docs explain how an entry array is handled:
What happens when you pass an array to entry? Passing an array of file
paths to the entry property creates what is known as a "multi-main
entry". This is useful when you would like to inject multiple
dependent files together and graph their dependencies into one
"chunk".
Webpack.config.js
require("babel-polyfill");
var config = {
devtool: 'cheap-module-eval-source-map',
entry: {
main: [
// configuration for babel6
['babel-polyfill', './src/js/main.js']
]
},
}
Alternative to Webpack - load babel-polyfill as an external script in the browser html
The alternative to using webpack would mean including the module as an external script in your html. It will then be available to code in the browser but the webpack bundle won't be directly aware of it.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.22.0/polyfill.js"></script>

Using webpack to simply transpile and concat files?

So i am trying to figure out how to use webpack to replace our current brunch build process. Basically we have an angular 1 app which doesnt utilise requires or imports at all and I want to have webpack just concat+transpile the files (there are both coffee and sass files and ill need to be able to watch and create source maps using the usual settings). This angular app is sitting inside another application which is using webpack extensively.
What is the simplest way to accomplish this? Is this even possible without the app using any form of javascript modules?
Here is my current config:
var webpack = require( "webpack" );
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require("path");
var glob = require("glob");
const exportConfig = {
entry: {
app: glob.sync('./front-end/applications/core/app/**/*.coffee'),
vendor: ['angular']
},
output: {
filename: "app.bundle.js",
path: path.join( __dirname, "../www_root/build" ),
},
debug: true,
module: {
loaders: [
{
test: /\.coffee$/,
loader: "coffee-loader"
},
{
test: /\.sass$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.(jsx|es6)/,
exclude: /(node_modules|www_root\/bower)/,
loader: "babel",
},
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
new ExtractTextPlugin("[name].css", {
allChunks: true
}),
]
}
module.exports = exportConfig
I basically just get an output file with an error for each of the files obviously:
(function webpackMissingModule() { throw new Error("Cannot find module \"./front-end/applications/core/app/components/app/module.coffee\""); }());
Thanks!

Categories