How to configure webpack devServer port? - docker

I'm trying to use webpack in my Symfony app in docker, but I'm still getting error:
GET http://localhost:8000/sockjs-node/info?t=1556798329924 404 (Not Found)
Everything works fine axcepts this error...
App is running on port 8000 and node on port 8081. The address with 8081 port is accessible, but how can I tell webpack to use port 8081 with devServer?
Here is my webpack.config.js:
const Encore = require('#symfony/webpack-encore');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const outputPath = './public/build/';
const publicPath = '/build';
Encore
.setOutputPath(outputPath)
.setPublicPath(publicPath)
// Clean output dir before build
.cleanupOutputBeforeBuild()
.splitEntryChunks()
.enableSingleRuntimeChunk()
// uncomment if you're having problems with a jQuery plugin
.autoProvidejQuery()
// Generate JS files
.addEntry('loader', './assets/javascript/loader.js')
.addEntry('admin-loader', './assets/javascript/admin.js')
// Generate CSS files
.addStyleEntry('forms', './assets/styles/forms.scss')
.addStyleEntry('grid', './assets/styles/grid.scss')
.addStyleEntry('reboot', './assets/styles/reboot.scss')
.addStyleEntry('styles', './assets/styles/styles.scss')
.addStyleEntry('utilities', './assets/styles/utilities.scss')
.addStyleEntry('admin', './assets/styles/admin.scss')
.enableEslintLoader()
.configureTerserPlugin((options) => {
options.cache = true;
options.parallel = true;
options.terserOptions = {
output: {
comments: false,
}
}
})
.configureSplitChunks((options) => {
options.chunks = 'all',
options.maxInitialRequests = Infinity,
options.cacheGroups = {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `pckg.${packageName.replace('#', '')}`;
},
}
}
})
// Enable SASS loader with PostCSS config
.enableSassLoader()
.enablePostCssLoader()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
// CSS Hot Loader for HMR in webpack dev server
.addLoader({
enforce: 'post',
test: /\.(s?c|sa)ss$/,
exclude: /node_modules/,
loader: 'css-hot-loader',
})
.addPlugin(new StyleLintPlugin({
lintDirtyModulesOnly: Encore.isProduction(),
context: './assets/styles/',
quiet: false,
}));
const config = Encore.getWebpackConfig();
// Export settings and generate files
module.exports = config;
Does anyone know?

Related

remoteEntry.js not found on Jenkins

We are deploying a remote app written in NextJS and Typescript; The host app is in React only.
Currently the host app gets a 404 not found error as the remote app runs into this error in the Build Snapshot on Jenkins
+ ls ./dist/static/chunks/remoteEntry.js
ls: cannot access './dist/static/chunks/remoteEntry.js': No such file or directory
script returned exit code 2
However, the file is generated locally and both apps are able to spin up in local environment.
Here is our next.config.js:
const NextFederationPlugin = require('#module-federation/nextjs-mf');
const { exposedModules } = require('./lib/routes');
const version = process.env.VERSION_OVERRIDE || require('./package.json').version;
const deps = require('./package.json').dependencies;
// Note: This path needs to match with what's specified in CIRRUS_FRONTEND_ENTRYPOINT for www.
const assetBasePath = process.env.CDN_PATH ? `${process.env.CDN_PATH}${version}` : process.env.ASSET_BASE_PATH;
// Note: Heavily references module federation example meant for omnidirectional federation between Next apps.
// Changes mostly around path resolution due to our current resolution pattern via cdn
// https://github.com/module-federation/module-federation-examples/blob/master/nextjs/home/next.config.js
module.exports = {
webpack(config, options) {
Object.assign(config.experiments, { topLevelAwait: true });
// Integrated mode calls `next build` which has minimization by default. For local development, this is unnecessary.
if (process.env.NEXT_PUBLIC_ENVIRONMENT === 'INTEGRATED') {
config.optimization.minimize = false;
}
if (!options.isServer) {
console.log("Not Server");
config.output.publicPath = 'auto';
config.plugins.push(
new NextFederationPlugin({
name: 'cirrus',
filename: 'static/chunks/remoteEntry.js',
exposes: {
'./FederatedRouter': './lib/FederatedRouter',
...exposedModules
},
remoteType: 'var',
remotes: {},
shared: {
'#transcriptic/amino': {
requiredVersion: deps['#transcriptic/amino'],
singleton: true
},
react: {
requiredVersion: deps.react,
singleton: true
},
'react-dom': {
requiredVersion: deps['react-dom'],
singleton: true
},
'#strateos/micro-apps-utils': {
requiredVersion: deps['#strateos/micro-apps-utils'],
singleton: true
}
},
extraOptions: {
// We need to override the default module sharing behavior of this plugin as that assumes a nextjs host
// and thus next modules will be provided by the parent application.
// However, web is currently NOT a nextjs application so this child application so that assumption is
// invalid. Note that this means we need to ensure we explicitly specify common modules such as `react`
// in the `shared` key above.
skipSharingNextInternals: true
}
})
);
} else {
console.log("Is Server");
}
return config;
},
// Note: Annoyingly, NextJS automatically automatically appends a `_next` directory for assetPrefix
// but NOT public path so we'll have to manually include it here.
publicPath: `${assetBasePath}/_next/`,
// Note: If serving assets via CDN, assetPrefix is required to help resolve static assets.
// Also, NextJS automatically appends and expects a `_next` directory to the assetPrefix path.
// See https://nextjs.org/docs/api-reference/next.config.js/cdn-support-with-asset-prefix
assetPrefix: process.env.CDN_PATH ? assetBasePath : undefined,
distDir: 'dist',
// Use index react-router as fallback for resolving any pages that are not directly specified
async rewrites() {
return {
fallback: [
{
source: '/:path*',
destination: '/'
}
]
};
}
};
Tried upgrade NextJS from 12.1.6 to 12.2.2
Tried upgrade Webpack from 5.74.0 to 5.75.0
Cleaned cache by sh 'yarn cache clean'
Tried clear env by sh 'env -i PATH=$PATH make build-snapshot'
Hash of node modules by tar -cf - node_modules | md5sum
Downgraded "#module-federation/nextjs-mf" from 5.12.9 to 5.10.5
Verified file writing permission

Browsersync is running but does not refresh the page

I have MacOS + installed Docker container by Mark Shust (https://github.com/markshust/docker-magento) + installed browsersync on the host.
Magento has ".less" files in the folder: app/design/frontend. I set a folder as a current one in the cli. And run this command from the host:
browser-sync start --host "domain.test" --proxy "https://domain.test" --files "**/*.less" --https
I get this output:
[Browsersync] Proxying: https://domain.test
[Browsersync] Access URLs:
--------------------------------------
Local: https://localhost:3000
External: https://domain.test:3000
--------------------------------------
UI: http://localhost:3002
UI External: http://localhost:3002
--------------------------------------
[Browsersync] Watching files...
I can open https://domain.test and it works properly. http://localhost:3002 shows that there are no current connections. However, the output in the cli infoms: "[Browsersync] Reloading Browsers..."
if i change less, i still can find changes on the website but only after a manual reload.
The documentation mentions grunt configuration and there are some recipes as an example. I tried to use standard magento's file but it does not help. It looks like this:
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
watch: {
files: 'app/design/**/*.less',
tasks: ['less']
},
browserSync: {
dev: {
bsFiles: {
src : [
'app/design/**/*.css'
]
},
options: {
watchTask: true,
server: './'
}
}
}
});
// load npm tasks
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
// define default task
grunt.registerTask('default', ['browserSync', 'watch']);
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function (task) {
return task.replace('.js', '');
});
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'cssmin',
'usebanner'
].map(function (task) {
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function (theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});};
Should it work without gruntjs running? And why the page reload is not triggered?
PS: I did not place this question into https://magento.stackexchange.com/ cause i believe it's a general problem and not related to Magento.

Using <style lang="scss"> in vue component gives error

I am trying to use vue js in rails.
Everything works, except when I tried to use <style> inside .vue component
The exact error is:
./app/javascript/layouts/dashboard.vue?vue&type=style&index=0&lang=scss& (./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/sass-loader/dist/cjs.js??ref--1-2!./node_modules/style-loader/dist!./node_modules/css-loader/dist/cjs.js??ref--5-1!./node_modules/postcss-loader/src??ref--5-2!./node_modules/sass-loader/dist/cjs.js??ref--5-3!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/layouts/dashboard.vue?vue&type=style&index=0&lang=scss&)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected newline.
My environment.js file
const { environment } = require('#rails/webpacker')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoader = require('./loaders/vueLoader')
const vuetifyLoader = require('./loaders/vuetifyLoader')
environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())
environment.loaders.prepend('vue', vueLoader)
environment.loaders.prepend('vuetify', vuetifyLoader)
const resolver = {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}
environment.config.merge(resolver)
module.exports = environment
VuetifyLoader.js file
module.exports = {
test: /\.s(c|a)ss$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
// Requires sass-loader#^7.0.0
options: {
implementation: require('sass'),
fiber: require('fibers'),
indentedSyntax: true // optional
},
// Requires sass-loader#^8.0.0
options: {
implementation: require('sass'),
sassOptions: {
fiber: require('fibers'),
indentedSyntax: true // optional
},
},
},
],
}
install these two plugins.
npm install --save node-sass
npm install --save sass-loader
So, the problem was with fiber and indentedSyntax. After removing those two, everything works as expected. I was getting lots of error related to scss like
like
expected new line
in sass files inside node_modules. I don't know, why vuetify recommends to use fiber in sass loader.

Webpack2 cannot resolve: config.context absolute path

I am trying to run my webpack config file (see below), but I am still getting certain type of errors that reffers to a paths I use in my webpack settings:
- config.context
- config.module.rules
- config.output
My idea was, that I set up my config.context path absolutely (as it is written in docs), otherwise my webpack.config files reffers to node_modules in parents directory. But still, when I run webpack -w --env.dev command, it throws following errors:
It seems to me, that config.context cant handle absolute path as it should. Any help how to set up paths correctly? Thank you!
My webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractText = require('extract-text-webpack-plugin');
module.exports = function (env) {
var project = {
env: env.prod ? 'prod' : 'dev',
jsBase: './routesMap/',
cssBase: './src/css/'
}
var config = {
context: path.resolve(__dirname),
entry: {
'routesMap': project.jsBase + 'main.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: '[name].js'
},
plugins: [
new ExtractText({
filename: 'styles.min.css',
disable: false,
allChunks: true
})
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, '/routesMap'),
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['es2015'],
plugins: ["transform-runtime"]
}
}
]
}
};
return config;
}
That's an issue with the latest webpack version. Try using uppercase drive letters in shell, e.g. C:/ instead c:/.
More info https://github.com/webpack/webpack/issues/4530.
I uninstalled latest webpack version (I had webpack 2.3.0) and installed version of 2.2.0, problem solved! As #zemirco stated in his answer, it has something to do with casesensitive letters in absolute path. Unfortunatelly changing small letter to big one doesnt help for me, so I just changed webpack version.

Gulp build with browserify environment variable

I'm looking to include either an environment variable or file that my modules can access for conditional flow.
// contains env build specific data
// or value 'develop' || 'production'
var env = require('config');
I know I can access the CL arguments with yargs which is great, but I can't seem to find a way to get arguments into my browserify build.
var bundleStream = {
cache: {},
packageCache: {},
fullPaths: false,
entries: [filename],
extensions: config.extensions,
debug: config.debug,
paths: ['./node_modules', './app/js/'],
require: ['jquery', 'lodash']
};
var bundle = function() {
bundleLogger.start(filename);
return bundleStream
.bundle()
.on('error', handleErrors)
.pipe(source(filename.replace('-app', '-bundle')))
.pipe(gulp.dest(process.cwd()))
.on('end', reportFinished)
.pipe(browserSync.reload({
stream: true
}));
};
You could create a config.json file dynamically, and then require it in your modules:
var fs = require('fs');
var gutil = require('gulp-utils');
gulp.task('create-config', function(cb) {
fs.writeFile('config.json', JSON.stringify({
env: gutil.env.env,
tacos: 'delicious'
}), cb);
});
gulp.task('browserify', ['create-config'], function() {
//...
});
In your modules:
var config = require('./config.json');
if (config.env === 'production') {
//...
}
And on the command line:
gulp --env=production

Resources