Reference snapshot of error -->>
Cannot set property 'styles' of undefined, error in nextJs
whenever I installs package or simply doing npm i I face this issue, I have tried
//next.config.js module.exports = withPlugins([...], {webpack5: false,}) and yarn add --dev webpack#webpack-4 less less-loader#5
but none of them solved the issue later on digging on issue came to know that #zeit\next-css have been deprecated, below is the next.config.js reference please let me know how to resolve issue, how to update code in config file so that I can use built-in CSS support of nextJs itself leaving behind the deprecated one, Very very Thanks in Advance.
const withSass = require('#zeit/next-sass');
const withCSS = require('#zeit/next-css');
const path = require('path');
module.exports = withCSS(
withSass({
webpack: (config) => {
config.node = {
fs: 'empty'
};
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
limit: 1000000,
name: '[name].[ext]'
}
},
{
loader: 'url-loader',
options: {
limit: 1000000,
name: '[name].[ext]'
}
}
]
});
module.exports = {
resolve: {
alias: {
TweenLite: path.resolve('node_modules', 'gsap/src/uncompressed/TweenLite.js'),
TweenMax: path.resolve('node_modules', 'gsap/src/uncompressed/TweenMax.js'),
TimelineLite: path.resolve('node_modules', 'gsap/src/uncompressed/TimelineLite.js'),
TimelineMax: path.resolve('node_modules', 'gsap/src/uncompressed/TimelineMax.js'),
ScrollMagic: path.resolve('node_modules', 'scrollmagic/scrollmagic/uncompressed/ScrollMagic.js'),
'animation.gsap': path.resolve(
'node_modules',
'scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js'
),
'debug.addIndicators': path.resolve(
'node_modules',
'scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js'
)
}
}
};
return config;
}
})
);
In webpack, CopyWebpackPlugin causes infinite loop when webpack is in watch mode. I tried to add watchOptions.ignored option but it doesn't seem to work.
My webpack config is following:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const config = {
entry: {
'res': './src/index.js'
},
output: {
filename: '[name].min.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'production',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new CopyWebpackPlugin([
{ from: 'dist', to: path.resolve(__dirname, 'docs/js') }
], {})
],
watchOptions: {
ignored: path.resolve(__dirname, 'docs/js')
}
};
module.exports = config;
Any help would be appreciated.
With CopyWebpackPlugin, I've experienced the infinite loop too. I tried all kinds of CopyWebpackPlugin configurations with no luck yet. After hours of wasted time I found I could hook into the compiler and fire off my own copy method.
Running Watch
I'm using webpack watch to watch for changes. In the package.json, I use this config so I can run npm run webpackdev, and it will watch for file changes.
"webpackdev": "cross-env webpack --env.environment=development --env.basehref=/ --watch"
My Workaround
I've added an inline plugin with a compiler hook, which taps into AfterEmitPlugin. This allows me to copy after my sources have been generated after the compile. This method works great to copy my npm build output to my maven target webapp folder.
// Inline custom plugin - will copy to the target web app folder
// 1. Run npm install fs-extra
// 2. Add fix the path, so that it copies to the server's build webapp folder
{
apply: (compiler) => {
compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
// Debugging
console.log("########-------------->>>>> Finished Ext JS Compile <<<<<------------#######");
let source = __dirname + '/build/';
// TODO Set the path to your webapp build
let destination = __dirname + '/../dash-metrics-server/target/metrics-dash';
let options = {
overwrite: true
};
fs.copy(source, destination, options, err => {
if (err) return console.error(err) {
console.log('Copy build success!');
}
})
});
}
}
The Workaround Source
Here's my webpack.config.js in total for more context. (In this webpack configuration, I'm using Sencha's Ext JS ExtWebComponents as the basis.)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BaseHrefWebpackPlugin } = require('base-href-webpack-plugin');
const ExtWebpackPlugin = require('#sencha/ext-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const fs = require('fs-extra');
module.exports = function(env) {
function get(it, val) {if(env == undefined) {return val;} else if(env[it] == undefined) {return val;} else {return env[it];}}
var profile = get('profile', '');
var emit = get('emit', 'yes');
var environment = get('environment', 'development');
var treeshake = get('treeshake', 'no');
var browser = 'no'; // get('browser', 'no');
var watch = get('watch', 'yes');
var verbose = get('verbose', 'no');
var basehref = get('basehref', '/');
var build_v = get('build_v', '7.0.0.0');
const isProd = environment === 'production';
const outputFolder = 'build';
const plugins = [
new HtmlWebpackPlugin({template: 'index.html', hash: false, inject: 'body'}),
new BaseHrefWebpackPlugin({ baseHref: basehref }),
new ExtWebpackPlugin({
framework: 'web-components',
toolkit: 'modern',
theme: 'theme-material',
emit: emit,
script: './extract-code.js',
port: 8080,
packages: [
'renderercell',
'font-ext',
'ux',
'd3',
'pivot-d3',
'font-awesome',
'exporter',
'pivot',
'calendar',
'charts',
'treegrid',
'froala-editor'
],
profile: profile,
environment: environment,
treeshake: treeshake,
browser: browser,
watch: watch,
verbose: verbose,
inject: 'yes',
intellishake: 'no'
}),
new CopyWebpackPlugin([{
from: '../node_modules/#webcomponents/webcomponentsjs/webcomponents-bundle.js',
to: './webcomponents-bundle.js'
}]),
new CopyWebpackPlugin([{
from: '../node_modules/#webcomponents/webcomponentsjs/webcomponents-bundle.js.map',
to: './webcomponents-bundle.js.map'
}]),
// Debug purposes only, injected via script: npm run-script buildexample -- --env.build_v=<full version here in format maj.min.patch.build>
new webpack.DefinePlugin({
BUILD_VERSION: JSON.stringify(build_v)
}),
// This causes infinite loop, so I can't use this plugin.
// new CopyWebpackPlugin([{
// from: __dirname + '/build/',
// to: __dirname + '/../dash-metrics-server/target/test1'
// }]),
// Inline custom plugin - will copy to the target web app folder
// 1. Run npm install fs-extra
// 2. Add fix the path, so that it copies to the server's build webapp folder
{
apply: (compiler) => {
compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
// Debugging
console.log("########-------------->>>>> Finished Ext JS Compile <<<<<------------#######");
let source = __dirname + '/build/';
// TODO Set the path to your webapp build
let destination = __dirname + '/../dash-metrics-server/target/metrics-dash';
let options = {
overwrite: true
};
fs.copy(source, destination, options, err => {
if (err) return console.error(err)
console.log('Copy build success!');
})
});
}
}
];
return {
mode: environment,
devtool: (environment === 'development') ? 'inline-source-map' : false,
context: path.join(__dirname, './src'),
//entry: './index.js',
entry: {
// ewc: './ewc.js',
app: './index.js'
},
output: {
path: path.join(__dirname, outputFolder),
filename: '[name].js'
},
plugins: plugins,
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/,
use: [
'babel-loader',
// 'eslint-loader'
]
},
{ test: /\.(html)$/, use: { loader: 'html-loader' } },
{
test: /\.(css|scss)$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'sass-loader' }
]
}
]
},
performance: { hints: false },
stats: 'none',
optimization: { noEmitOnErrors: true },
node: false
};
};
So I know this question is very old at this point, but I was running into this endless loop issue again recently and found a couple of solutions.
Not the cleanest method, but if you add an "assets" folder, which can be completely empty, to the root of your project, it seems to only compile after your sources folder changes.
The better method I have found is within the webpack config. The original poster mentioned about using ignored which does seem to fix the issue if you instruct webpack to watch file changes after the initial build and to ignore your dist/output folder...
module.exports = {
//...
watch: true,
watchOptions: {
ignored: ['**/dist/**', '**/node_modules'],
},
};
I want to build my js code with react and others and minify it to one file.
It works well but I get the development version of react
It looks like you're using a minified copy of the development build of React
Now I know I need to add NODE_ENV = production
but I tried in so many ways and still, the build stays the same...
I tried envify as you can see below, and hardcoding it like this:
process.env.NODE_ENV = 'production';
but still, not good.
When I try to add envify transform, with that:
.transform(envify({
'NODE_ENV': 'production'
}))
I get this error on the build:
TypeError Path must be a string.
any ideas?
function bundleJs() {
const _browserify = browserify({
entries: [config.entry],
debug : false,
cache: {},
packageCache: {},
fullPaths: true,
extensions: ['.js']
});
_browserify.plugin(resolutions, ['*'])
.transform('envify', {global: true, _: 'purge', NODE_ENV: 'production'})
.transform(hbsfy)
.transform(babelify, {
only: /(app)|(frontend-app)/,
presets: ['es2015-without-strict', 'react']
})
.on('update', () => {
bundle();
gutil.log('Rebundle...');
})
.on('log', gutil.log);
function bundle() {
return bundler.bundle()
.on('error', handleError)
.pipe(source('init.js'))
.pipe(rename('bundle.js'))
.pipe(buffer())
.pipe(gulpif(env === 'production', uglify()))
.pipe(gulpif(env !== 'production', sourcemaps.init({ loadMaps: true })))
.pipe(gulpif(env !== 'production', sourcemaps.write('.')))
.pipe(gulp.dest(config.dist))
.pipe(browserSync.reload({stream:true}));
}
// run it once the first time buildJs is called
return bundle();
}
OK, so after wasting 3 hours of my life on that code.
I noticed that the build of react is used from bower and not from npm.
inside composer.json we had identifieres under "browser", ie:
"react": "./bower_components/react/react.js",
"react-dom": "./bower_components/react/react-dom.js"
I assume this points directly to react dev build so that was the problem.
I simply installed with npm, and all worked well.
I'm trying to set my project's gulp tasks in order and this how my gulpfile.js code looks currently:
var gulp = require('gulp'),
nodemon = require('gulp-nodemon'),
webpack = require('gulp-webpack');
gulp.task('nodemon', ['webpack'], function(){
console.log('NODEMON');
return nodemon({
script: 'server/server.js',
ext: 'js',
ignore: [
'client/game.js'
],
tasks: function(changedFiles){
var tasks = ['webpack'];
changedFiles.forEach(function(file){
console.log('changed file: ' + file);
});
return tasks;
},
env: { 'NODE_ENV': 'development' }
});
});
gulp.task('webpack', function(){
console.log('WEBPACK');
return gulp.src('src/main.js')
.pipe(webpack({
entry: `${__dirname}/src/main.js`,
output: {
path: `${__dirname}/client/`,
filename: 'game.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
}
}))
.pipe(gulp.dest('client/'));
});
gulp.task('default', ['webpack', 'nodemon'], function(){
console.log('DEFAULT');
});
First of all, everything works and that's fine. But when I modify my server.js file, it always triggers the onChange event twice causing the 'webpack' run and the server restart twice. What am I doing wrong?
Edit: The strange thing is that every time I modify a script, not only does it trigger the 'webpack' task run as it's supposed to be, but it also re-runs my gulpfile.js script, duplicating every task it runs, which is why the server starts twice. My problem now is why would gulpfile.js be run all over each time. This doesn't happen if I skip the tasks parameter.
So my app is running off a concatenated admin.bundle.js file. I'm using webpack to manage the modules, and then using gulp-webpack to import my webpack config, then run the sourcemap code:
gulp.task('webpack', function() {
return gulp.src('entry.js')
.pipe(webpack( require('./webpack.config.js') ))
.pipe(sourcemaps.init())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('app/assets/js'));
});
My Webpack config
var webpack = require('webpack');
module.exports = {
entry: "./entry.js",
output: {
pathinfo: true,
path: __dirname,
filename: "admin.bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
The problem is when I'm testing my app with ChromeDev tools, the break points in the individual app modules won't work. They only work when I look at the source for admin.bundle.js this isn't ideal as I need to search for a specific line in the code to goto :( instead of just having the break point happen inside of the module itself, which makes it easier and faster to debug.
Below the debugger is stopped on a function inside of the concatenated admin.bundle.js file
There is the tagsDirective.js module, this is where I expect the break point to happen :(
Anyone run into this problem before with Webpack and Gulp?
Screenshot of part of the admin.bundle and the map file:
Ah figured it out, I moved the sourcemap generation code back into webpack, and out of Gulp:
var webpack = require('webpack');
var PROD = JSON.parse(process.env.PROD_DEV || '0');
module.exports = {
entry: "./entry.js",
devtool: "source-map",
output: {
devtoolLineToLine: true,
sourceMapFilename: "admin.bundle.js.map",
pathinfo: true,
path: __dirname,
filename: PROD ? "admin.bundle.min.js" : "admin.bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: PROD ? [
new webpack.optimize.UglifyJsPlugin({minimize: true})
] : []
};
gulp.task('webpack', function() {
return gulp.src('entry.js')
.pipe(webpack( require('./webpack.config.js') ))
// .pipe(sourcemaps.init())
// .pipe(sourcemaps.write('./'))
.pipe(gulp.dest('app/assets/js'));
});