Webpack running through grunt webpack doesn't error or complete, or do anything - angularjs

Trying to convert an old system off bower into npm using webpack, and grunt webpack. Just trying to use webpack to load in NPM files, not run anything else, and the rest of the grunt file finishes loading and uglifying and stuff, and runs its own node server. It gets to this point and freezes and never comes back.
Loading "grunt-webpack" plugin
Registering "/Users/***/***/***/node_modules/grunt-webpack/tasks" tasks.
Loading "webpack-dev-server.js" tasks...OK
+ webpack-dev-server
Loading "webpack.js" tasks...OK
+ webpack
Running "webpack" task
Here's my grunt code (super basic obviously)
webpack: {
options: require("./config/webpack.dev.js"),
},
Here's that dev file
const webpack = require('webpack');
const helpers = require('./helpers');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BaseHrefWebpackPlugin } = require('base-href-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ConcatPlugin = require('webpack-concat-plugin');
const ngInventory = require('./ng1-vendor-index.js');
const common = require('./webpack.common.js');
const ENV = process.env.NODE_ENV = process.env.ENV = 'dev';
module.exports = merge(common(ENV), {
devtool: 'source-map',
module: {
rules: [
{
test: /\.(ts|js)$/,
loaders: ['angular-router-loader'],
},
{
test: /\.((s*)css)$/,
use: [{
loader: 'style-loader',
},{
loader: 'css-loader',
},{
loader: 'sass-loader',
}]
},
{
test: /src\/.+\.(ts|js)$/,
exclude: /(node_modules|\.spec\.ts$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post',
options: {
esModules: true
}
}
]
},
debug: true,
devTool: 'eval',
plugins: [
new ConcatPlugin({
uglify: false,
sourceMap: true,
name: 'vendor',
outputPath: './',
fileName: '[name].[hash].js',
filesToConcat: ngInventory.vendor1
}),
new BaseHrefWebpackPlugin({ baseHref: '/'}),
new HtmlWebpackPlugin({
favicon: helpers.root('client/assets/image/favicon.png'),
template: "./client/index.html",
filename: "./client/index.html",
}),
new webpack.NoEmitOnErrorsPlugin(),
],
});
And here is the common file:
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals')
const helpers = require('./helpers');
module.exports = env => ({
entry: {
server: './server/app.js',
},
resolve: {
extensions: ['.ts', '.js']
},
output: {
path: helpers.root(`dist/${env}`),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
},
externals: [nodeExternals()],
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
include: [
helpers.root('client'),
],
loader: 'html-loader'
},
{
test: /\.((s*)css)%/,
include: [
helpers.root('client/app'),
helpers.root('client/components'),
],
exclude: 'node_modules/',
loaders: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(woff|woff2|eot|tts)$/,
use: [{
loader: 'file-loader'
}]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(env)
}
}),
new webpack.ContextReplacementPlugin(/\#angular(\\|\/)core(\\|\/)esm5/, path.join(__dirname, './client')),
]
});
A sample from the vendor index file:
const helper = require('./helpers');
exports.vendor1 = [
helper.root('node_modules/lodash/lodash.js'),
helper.root('node_modules/lodash-deep/lodash-deep.js'),
...
...
]
I'm just really not sure what to do, couldn't bring up any google results or stack results because theres no errors happening either. I've tried all verbose levels of logging all to no avail. What in the world am I missing?

As the documentation shows, you haven't configured any targets, like dev or prod. You've only specified options. You want
webpack: {
options: {},
dev: require("./config/webpack.dev.js"),
},
As an aside, there's no benefit to using Webpack with Grunt.

Related

Webpack Source Map Export Compiled JS

I was using webpack 3, there was no hot reload issue and then I upgraded to webpack 5.
Webpack version: ^5.50.0, React version: 17.0.2
Webpack source map doesn't work properly. I attached a picture of output at the bottom.
When I read webpack documentation, there is no difference between my config with offical config.
Here is my webpack hot config for development;
const webpack = require('webpack') //to access built-in plugins
const HtmlWebpackPlugin = require('html-webpack-plugin') //installed via npm
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const vendorArray = require('./vendors')
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
main: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3002',
'webpack/hot/only-dev-server',
'./src/main.js'
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash:8].js'
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss', '.json']
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: './config/webpack/style-loader'
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env', { targets: 'defaults' }], '#babel/preset-react'],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-nullish-coalescing-operator',
[
'#babel/plugin-proposal-decorators',
{
legacy: true
}
]
]
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)([\?]?.*)$/,
type: 'asset/resource'
}
]
},
plugins: [
new webpack.DefinePlugin({
APP_ENV: JSON.stringify('dev')
}),
new HtmlWebpackPlugin({
template: './public/index.html',
templateParameters: {
recaptchaSiteKey: '6LfbRrEZAAAAAL1EiyUSq1yzEw1xqleak2xC2pzi',
intranetLogin: true
}
}),
new MiniCssExtractPlugin(),
new Dotenv({
path: path.resolve(__dirname, './../../.env.test')
})
]
}

Webpack 4 configuration for react-toolbox

I try to upgrade my app from webpack 2 to webpack 4.16.5.
Because I want not again end up in a hard to understand some hundreds line config, I start with a minimal config. This is my current:
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const context = path.resolve(__dirname, "app");
module.exports = {
entry: {
home: "./index.js"
},
context,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "postcss-loader"
},
{
loader: "sass-loader"
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
resolve: {
extensions: [".js", ".jsx", ".css", "json"],
modules: [path.resolve(__dirname, "node_modules"), context]
}
};
But I run in problems importing the CSS files from react-toolbox i.e.:
import Dialog from 'react-toolbox/lib/dialog';
in a js file and also
#import "react-toolbox/lib/button/theme.css";
causes errors like this:
ERROR in ../node_modules/react-toolbox/lib/switch/theme.css (../node_modules/css-loader!../node_modules/postcss-loader/src!../node_modules/sass-loader/lib/loader.js!../node_modules/react-toolbox/lib/switch/theme.css)
Module build failed (from ../node_modules/css-loader/index.js):
Error: composition is only allowed when the selector is single: local class name not in ".disabled", ".disabled" is weird
Does anyone have a working application with wbpack4 and react-toolbox? Also, any hints on what may cause these errors are welcome!
I'm learning react.js with the js stack from scratch tutorial and try to using react-toolbox components.
Finnaly, i have a working demo with webpack 4 and the react-toolbox, it's based on the react-toolbox-example.
This is my settings:
add css-modules related packages
$ npm install postcss postcss-cssnext postcss-import postcss-loader css-loader style-loader
add a postcss.config.js
module.exports = {
plugins: {
'postcss-import': {
root: __dirname,
},
'postcss-cssnext': {}
},
};
add a webpack rule
...
{ test: /\.css$/, use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]--[local]--[hash:base64:8]'
}
},
'postcss-loader'
]},
...
add cmrh.conf.js - Using the css-modules-require-hook for SSR(Optional)
module.exports = {
generateScopedName: '[name]--[local]--[hash:base64:8]'
}
You can see all the settings in here, hope it will work for you.

React, WebPack and Babel for Internet Explorer 10 and below produces SCRIPT1002: Syntax error

I've read multiple threads regarding similar issues and tried some propositions, but had no results.
I've followed few tutorials related to React.js and WebPack 3. As the result the application is working well on all browsers (at this moment) except IE 10 and below. The error points to bundle.js (once I'm using the configuration Nr.1):
SCRIPT1002: Syntax error and the line - const url = __webpack_require__(83);
With configuration Nr2., on local server - : SCRIPT1002: Syntax error - line with eval()
And the same configuration, but running on remote server produces a bit different error:
SCRIPT5009: 'Set' is undefine
WebPack configuration Nr1.:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.json$/,
exclude: /node_modules/,
loader: 'json-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
],
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
}
]
},
devServer: {
historyApiFallback: true,
contentBase: './'
},
plugins: [HtmlWebpackPluginConfig]
}
WebPack configuration Nr2.:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname);
const buildPath = path.join(__dirname, 'dist');
module.exports = {
stats: {
warnings: false
},
devtool: 'cheap-eval-source-map',
devServer: {
historyApiFallback: true,
contentBase: './'
},
entry: {
app: path.resolve(sourcePath, 'index.js')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks: Infinity
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
path: buildPath,
excludeChunks: ['base'],
filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'all',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new webpack.NoEmitOnErrorsPlugin(),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react', 'es2015'],
plugins: ["transform-es2015-arrow-functions"]
}
},
include: sourcePath
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { minimize: true } },
'postcss-loader',
'sass-loader'
]
})
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};
Here additionally I've added the es2015 to presets: ['env', 'react', 'es2015'] and plugins: ["transform-es2015-arrow-functions"] but it made no sense.
Well in case when the babel loader won't work at all of misconfiguration or something else, I think that the whole application won't start. I believe that something should be done with presets or their order... Need advice from experienced developer
UPDATE
I've changed devtool to inline-cheap-module-source-map and got error point to overlay.js -> const ansiHTML = require('ansi-html');
In your package.json file
change the version of webpack-dev-server to version "2.7.1" (or earlier).
"webpack-dev-server": "2.7.1"
Then do a npm install et voilà.
That solved the problem for me.
All versions after 2.7.1 gives me an error similar to yours.
Simply add devtools : "source-map" to your Webpack config like this:
const path = require('path');
module.exports = {
devtool: "source-map",
entry: ['babel-polyfill', path.resolve(__dirname, './js/main.js')],
mode: 'production',
output: {
path: __dirname+'/js/',
filename: 'main-webpack.js'
}
};
This will remove eval and change your source map to be supported by IE.
UPDATE I've changed devtool to inline-cheap-module-source-map and got error point to overlay.js -> const ansiHTML = require('ansi-html');
And to support ES6 syntax you have to compile your JavaScript code with Babel.

React error even after using DefinePlugin

I am using React 15.4.2 and Redux 3.6.0 with Webpack and this is my webpack.config.js file contents: (some of the code is omitted for brevity)
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const pkg = require('./package.json');
const TARGET = process.env.npm_lifecycle_event;
const PATHS = {
src: path.join(__dirname, 'src/js'),
dist: path.join(__dirname, 'dist')
};
process.env.BABEL_ENV = TARGET;
const common = {
resolve: {
extensions: ['', '.js', '.jsx']
},
entry: {
app: PATHS.src
},
output: {
path: PATHS.dist,
publicPath: '/',
filename: '[name].[hash].js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loaders: ['babel?cacheDirectory'], include: PATHS.src },
{ test: /\.scss$/, exclude: /node_modules/, loaders: ['style', 'css', 'sass'] },
{ test: /(\.ttf|\.woff2?|\.eot|\.svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, exclude: /node_modules/, loader: 'url' },
{ test: /\.(jpe?g|png|gif|svg)$/i, exclude: /node_modules/, loader: 'url?limit=10000!img?progressive=true' },
{ test: /\.json/, loaders: ['json']}
]
},
plugins: [
new HTMLWebpackPlugin({
template: 'src/index.html',
inject: 'body'
})
]
};
if (TARGET === 'build') {
module.exports = merge(common, {
entry: {
vendor: Object.keys(pkg.dependencies)
},
output: {
path: PATHS.dist,
filename: '[name].[chunkhash].js',
chunkFilename: '[chunkhash].js'
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextWebpackPlugin.extract('style', 'css'), include: PATHS.src }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new CleanWebpackPlugin([PATHS.dist]),
new ExtractTextWebpackPlugin('[name].[chunkhash].css'),
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
})
]
});
}
Running npm run build gives the minified code. But it still gives the error
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See https://facebook.github.io/react/docs/optimizing-performance.html#use-the-production-build for more details.
I have also tried reordering the plugins in build TARGET, but its giving the same error.
What am I missing here?
P.S. Redux gives the same minification error too.
EDIT
This is my package.json build script:
"scripts": {
...
"build": "NODE_ENV=production webpack --progress"
...
}
EDIT #2
This is the output to a console.log statement from within the application.
You could use this syntax for the DefinePlugin.
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
I enabled source maps to see that its a package I have been using that was minified using non-standard ways. So, setting NODE_ENV to 'production' had no effect on the said package. Nevertheless, my Webpack config and my build scripts have been working perfectly fine. Thank you for your help guys!

Webpack -p doesn't create bundle correctly

I started learning React by myself and I decided to create a boilerplate for me. I'm getting a problem to build a project using webpack. When I run in dev mode, works fine. When I run the command 'postinstall' to build for production, it generates a bundle.js with only a few bytes. But when I run the 'postinstall' without the parameter -p, it generates my bundle with ~ 2MB, the same thing when generates for dev mode (obviously because is not set for production). I didn't figure out why the production flag isn't creating my bundle correct. Can someone help me with this problem?
The project is in the repository:
https://github.com/ribeiroguilherme/react-boilerplate-dashboard
The webpack.production.config.js file:
const webpack = require('webpack');
const path = require('path');
const ExtractPlugin = require('extract-text-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const plugins = [
new CleanPlugin('dist'),
new ExtractPlugin('bundle.css'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({ minimize: true }),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
];
module.exports = {
devtool: 'eval',
debug: false,
context: __dirname + '/src/client',
entry: {
javascript: './index.jsx',
html: './index.html',
},
output: {
filename: 'bundle.js',
path: __dirname + '/dist',
},
resolve: {
extensions: ['', '.js', '.jsx', '.json'],
root: path.resolve(__dirname, './src/client'),
},
eslint: {
configFile: './.eslintrc',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'eslint-loader',
},
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
},
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.css$/,
loader: ExtractPlugin.extract('style-loader', 'css-loader'),
},
],
},
plugins: plugins,
};
I'm also worried because the bundle looks pretty big for a project that I just started now. Any hints will be very appreciated.
Best Regards

Resources