Vite serves up jsx files in network traffic - vite

I'm not sure what is going on but I have a very basic Vite setup, yet I'm seeing the local server serve up all my jsx files, which takes a good 10-15s when I do a fresh reload. At first I thought this just might be the way Vite works for development but even when trying to build for production it does the same thing and doesn't minimize or uglify the files but just serves the jsx as is.
enter image description here
The following is my vite.config.js. The commented out code is other things that I've tried with no success:
export default ({mode}) => {
return defineConfig({
root: 'app',
define: {global: 'window'},
// esbuild: {
// loader: "jsx",
// minify: true,
// minifySyntax: true,
// },
// optimizeDeps: {
// esbuildOptions: {
// minify: true,
// minifySyntax: true,
// loader: {
// ".js": "jsx",
// ".ts": "tsx",
// },
// },
// },
plugins: [react()],
// build: {
// outDir: '../dist',
// minify: true,
// },
server: {
host: '127.0.0.1',
port: 3000
}
})
};
I've tried numerous configuration options and tried every rollup/vite config option I could find on stack overflow and the internet. I'd expect vite to serve only the produced index.html and generated index.jsx file, not get all my source files as is.
This project originally did use webpack, but even then I wasn't doing anything special. Here is my webpack config incase that's helpful:
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'development',
devtool: 'eval-source-map',
entry: [
'webpack-dev-server/client?http://vesta-dev.localhost.com:3000',
'webpack/hot/dev-server',
'react-hot-loader/patch',
path.join(__dirname, 'app/index.js')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name].[hash].js',
publicPath: '/'
},
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new webpack.DefinePlugin({
...
})
],
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
exclude: [/node_modules/, /__tests__/],
loader: 'eslint-loader',
options: {
configFile: path.resolve(__dirname, '.eslintrc'),
failOnWarning: false,
failOnError: false,
emitError: false,
emitWarning: true
}
},
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
cacheDirectory: true,
plugins: ['react-hot-loader/babel']
}
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.scss$/,
use: ['style-loader','css-loader','sass-loader?modules&localIdentName=[name]---[local]---[hash:base64:5]']
},
{ test: /\.(jpe?g|png|gif)$/i, loader: 'file-loader' },
{
test: /\.woff(2)?(\?[a-z0-9#=&.]+)?$/,
loader: 'url-loader',
options: {
limit: '10000',
mimetype: 'application/font-woff'
}
},
{ test: /\.(ttf|eot|svg)(\?[a-z0-9#=&.]+)?$/, loader: 'file-loader' },
]
}
};

Looks like this is normal for when you use vite serve as that always serves the development environment, no matter what flags you set or command line options you pass in.
I thought it was interesting that no one talks about the jsx files actually being served in the network traffic and even with all my searching never came across anyone talking about this, nor in the Vite documents so I thought something was wrong.

Related

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted - NodeJS, Express & Webpack

I am developing a web application using Node.js, Express & Webpack. Everything was going well until Webpack was upgraded to Webpack 5 and lots of bugs appeared. I have managed to solve all the errors but there is a warning I can't solve. I have seen this post but it's related to Angular so I don't think it helps me much: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
WARNING in ./node_modules/terser-webpack-plugin/dist/minify.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
This is my webpack.config.js; resolve fields and node-polyfill-webpack-plugin are used to solve Webpack 5 bugs and errors.
const path = require("path")
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
resolve:{
fallback: {
"fs": false,
"path": false,
"worker_threads":false,
"child_process":false,
"http": false,
"https": false,
"stream": false,
"crypto": false,
}
},
entry: {
main: './src/js/main.js',
index:'./src/js/'
},
output: {
path: path.join(__dirname, 'dist'),
//publicPath: '/',
filename: '[name].js'
},
mode:"development",
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.bpmn$/,
use: 'raw-loader'
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/index.ejs',
filename: "./index.ejs",
excludeChunks: [ 'server', 'main' ]
}),
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/bmv.ejs',
filename: "./bmv.ejs",
excludeChunks: [ 'server', 'index' ]
}),
new webpack.NoEmitOnErrorsPlugin(),
new NodePolyfillPlugin()
]
}
configure the webpack:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
'terser-webpack-plugin': path.resolve(__dirname, 'node_modules/terser-webpack-plugin/dist/minify.js'),
},
},
};

Webpack Babel build fails when importing files outside entry path

I have this project that i'm already using webpack + babel to build. I've hit a wall since what i want to do is share some constants between my node (server) and my react app (front-end).
My project structure is this
- app
- internals
- webpack
- different webpack configs (node, react-dev, react-production etc)
- server
- shared
- .babelrc
I've put some "constants" files into the shared folder that I use both from my app and from my server.
When I try to build my server I get this
ERROR in ./shared/reports.constants.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: Cannot read property 'code' of null
at transpile (C:\Users\XXX\Desktop\XXX\XXX\node_modules\babel-loader\lib\index.js:70:21)
at Object.module.exports (C:\Users\XXX\Desktop\XXX\XXX\node_modules\babel-loader\lib\index.js
:173:20)
Below is my webpack config file. Any ideas what might be wrong ?
{
mode: 'production',
target: 'node',
externals: nodeExternals(),
entry: {
server: [path.join(process.cwd(), 'server/index.js')],
},
output: {
filename: '[name].js',
path: path.resolve(process.cwd(), 'build'),
// sourceMapFilename: '[name].js.map',
},
devtool: 'hidden-source-map',
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract(
{ fallback: 'style-loader', use: { loader: 'css-loader', options: { minimize: true } } }),
},
{ test: /\.jpg$/, use: [{ loader: 'file-loader', options: { name: '/images/[name].[ext]' } }] },
{ test: /\.md$/, use: [{ loader: 'markdown-with-front-matter-loader' }] },
{
test: /\.js$/,
exclude: [/node_modules/],
include: [/server/, /shared/],
use: [
'babel-loader',
{
loader: 'webpack-preprocessor-loader',
options: {
debug: process.env.NODE_ENV !== 'production',
directives: {
secret: false,
},
params: {
ENV: process.env.NODE_ENV,
DEBUG: process.env.NODE_ENV !== 'production',
PRODUCTION: process.env.NODE_ENV === 'production',
ENVIRONMENT: process.env.ENVIRONMENT,
},
verbose: false,
},
},
],
},
],
},
plugins
etc
}
.babelrc file
{
"presets": [
"#babel/preset-env"
],
"plugins": [
"react-hot-loader/babel",
"#babel/transform-runtime",
"transform-html-import-to-string"
]
}
I've added the /shared/ to the includes rules.
Thank you in advance
For some reason I already had a babel.config.js + the babelrc. All I had to do was go into the babel.config.js and add the shared folder to be included in the env => production.
Thank you for your time

asset_url_for() returns None in flask cookie cutter (flask-webpack)

Im new to webpack. Im using flask-cookie-cutter which in turn uses Flask-Webpack
Im having issues in that App wont find my images in development.
Images are in assets/img folder
Ive tried using {{ asset_url_for('img/img_name.png') }} and various variations of it - and it just returns none.
Ive tried the usual flask way of {{ url_for('static', filename='img/img_name.png') }}
But I cant seem to access them.
const path = require('path');
const webpack = require('webpack');
/*
* Webpack Plugins
*/
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://0.0.0.0:2992' : '';
const rootAssetPath = path.join(__dirname, 'assets');
module.exports = {
// configuration
context: __dirname,
entry: {
main_js: './assets/js/main',
main_css: [
path.join(__dirname, 'node_modules', 'materialize-css', 'dist', 'css', 'materialize.css'),
path.join(__dirname, 'assets', 'css', 'style.css'),
],
},
output: {
path: path.join(__dirname, 'dsi_website', 'static', 'build'),
publicPath: `${publicHost}/static/build/`,
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].js',
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
devtool: 'source-map',
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' },
},
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader!less-loader',
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader',
],
},
{
test: /\.html$/,
loader: 'raw-loader'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i,
loader: `file-loader?context=${rootAssetPath}&name=[path][name].[hash].[ext]`
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env'],
cacheDirectory: true
}
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[hash].css', }),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new ManifestRevisionPlugin(path.join(__dirname, 'dsi_website', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
]),
};
I was the same problem with flask-cookie-cutter and solve it by update/upgrade npm and add extensionsRegex: /\.(jpe?g|png|gif|svg)$/i at down file: webpack.config.js like this:
ManifestRevisionPlugin(path.join(__dirname, '<your app>', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
extensionsRegex: /\.(jpe?g|png|gif|svg)$/i
}),
source solution. Proper call to show image in temaplate:
{{ asset_url_for('img/img_name.png') }}
after that i check startup screen and i see that all my images load properly
[WEBPACK] _/assets/img/image_name.20aed528d50316c91ffedb5ba47b8c74.jpg 18.9 KiB [emitted]

Extract local and global styles with mini-css-extract-plugin

Until now I have been using extract-text-webpack-plugin and webpack 3 to make two bundle files. One for local styles and one for gloabl styles.
So in global styles file we would extract css from like bootstrap, semantic ... and in local styles bundle we would put our own styles.
Both of those files would have contenthash so if for example I change something in my local styles and rebuild app, only the hash from local styles would change and not from globaly styles.
After updateing to webpack 4 a need to use mini-css-extract-plugin instead of extract-text-webpack-plugin.
This was my setup until now. I am trying different things but I dont know how to turn this setup for mini-css-extract-plugin?
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ExtractLocal = new ExtractTextPlugin({
filename: 'stylesheet/stylesLocal.[contenthash].local.css',
disable: false,
allChunks: true,
})
const ExtractGlobal = new ExtractTextPlugin({
filename: 'stylesheet/stylesGlobal.[contenthash].css',
disable: false,
allChunks: true,
})
module.exports = {
module: {
rules: [
/* Local styles */
{
test: /\.local\.(css|scss)$/,
use: ExtractLocal.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize: true,
modules: true,
importLoaders: 1,
localIdentName: '[local]___[name]__[hash:base64:5]',
},
},
...
],
}),
},
/* Global styles */
{
test: /^((?!\.local).)+\.(css)$/,
use: ExtractGlobal.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize: true,
},
},
],
}),
},
],
},
plugins: [
ExtractLocal,
ExtractGlobal,
...
],
}
Your css loaders are correct.
In plugins, I see you want implement it using mini-css to extract multiple css files.
While it's definitely an options, I succeeded implementing it with webpack Optimization option, and only 1 mini-css in plugins.
Output config:
output: {
path: appConfig.paths.appBuild,
filename: 'scripts/[name].[chunkhash:8].js',
chunkFilename: 'scripts/[name].[chunkhash:8].chunk.js',
publicPath: publicPath,
},
Additional css rule for styles from node modules only (I made it the first css rule and after it the additional rules):
{
test: /\.(css|scss)$/,
include: /(node_modules)/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
Optimization config:
(This will extract vendor js as well.)
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
Plugin config:
new MiniCssExtractPlugin({
filename: 'styles/[name].[contenthash].css',
chunkFilename: 'styles/[name].[contenthash].css',
}),

"npm run" hanging on ts-loader (webpack)

I am building a web app that consists of static HTML and other assets using webpack on Mac OS X 10.11.3. The app talks to an API that is on another server.
I am having trouble building my app using webpack. The build process appears to hang at or around the ts-loader execution. I am running my build like this:
npm run go --loglevel verbose
which executes this command from my package.json:
./node_modules/.bin/webpack-dev-server --display-reasons --display-chunks --watch
The output in the Terminal window ends with
ts-loader: Using typescript#1.7.5 and /Users/mn/Documents/source/J/appstore/store-front/app/ts/tsconfig.json
I have tried deleting the node_modules folder and reinstalling these; I have tried uninstalling webpack and reinstalling; I have tried reverting my webpack.config.js to a version I know works; but it just hangs here!
My webpack.config.js looks like this:
var webpack = require('webpack'),
ReloadPlugin = require('webpack-reload-plugin'),
path = require('path'),
ChunkManifestPlugin = require('chunk-manifest-webpack-plugin'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
WebpackNotifierPlugin = require('webpack-notifier'),
ExtractTextPlugin = require("extract-text-webpack-plugin");
/**
* optimist has been depracted. Find an alternative? minimist?
*/
var argv = require('optimist')
.alias('r', 'release').default('r', false)
.argv;
/**
* Useful variables
*/
var cwd = process.cwd();
var DEBUG = !argv.release;
var isDevServer = process.argv.join('').indexOf('webpack-dev-server') > -1;
var version = require(path.resolve(cwd, 'package.json')).version;
var reloadHost = "0.0.0.0";
var npmRoot = __dirname + "/node_modules";
var appDir = __dirname + "/app";
var entry = ["./app/ts/bootstrap"]
if (isDevServer) {
entry.unshift("webpack-dev-server/client?http://" + reloadHost + ":8080");
}
function makeConfig(options) {
return {
cache: true,
debug: true,
verbose: true,
displayErrorDetails: true,
displayReasons: true,
displayChunks: true,
context: __dirname,
entry: {
app: entry,
vendor: './app/ts/vendor.ts'
},
stats: {
colors: true,
reasons: DEBUG
},
devtool: 'source-map',
recordsPath: path.resolve('.webpack.json'),
devServer: {
inline: true,
colors: true,
contentBase: path.resolve(cwd, "build"),
publicPath: "/"
},
output: {
path: path.resolve(cwd, "build"),
filename: "[name].js",
publicPath: "/",
chunkFilename: "[id].bundle.js",
// Hot Module Replacement settings:
hotUpdateMainFilename: "updates/[hash].update.json",
hotUpdateChunkFilename: "updates/[hash].[id].update.js"
},
plugins: [
new webpack.IgnorePlugin(/spec\.js$/),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] }),
new ExtractTextPlugin("styles.css"),
new webpack.DefinePlugin({
VERSION: JSON.stringify(version),
ENV: JSON.stringify(options.env)
}),
new HtmlWebpackPlugin({
template: path.join(appDir, "index.html"),
}),
new ReloadPlugin(isDevServer ? 'localhost' : ''),
new WebpackNotifierPlugin({
title: "Jisc AppStore App"
}),
],
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
modulesDirectories: ['node_modules'],
fallback: path.join(__dirname, "node_modules")
},
resolve: {
root: [path.resolve(cwd)],
modulesDirectories: [
'node_modules', 'app', 'app/ts', '.'
],
extensions: ["", ".ts", ".js", ".json", ".css"],
alias: {
'app': 'app',
'scripts': npmRoot
}
},
module: {
preLoaders: [
{ test: /\.ts$/, loader: "tslint" }
],
loaders: [
{ test: /\.(png|jp?g|gif)$/, loaders: ["url", "image"] },
{ test: /\.json$/, loader: 'json' },
{ test: /^(?!.*\.min\.css$).*\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader?sourceMap") },
{ test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap'] },
å { test: /\.html$/, loader: "html" },
{ test: /\.ts$/, loader: 'ts', exclude: [/test/, /node_modules/] },
{ test: /vendor\/.*\.(css|js)/, loader: 'file-loader?name=[path][name].[ext]', exclude: [/node_modules/] },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
],
noParse: [
/\.min\.js/,
/vendor[\/\\].*?\.(js|css)$/
]
},
tslint: {
emitErrors: false,
failOnHint: false
}
}
}
var config = makeConfig(argv)
console.log(require('util').inspect(config, { depth: 10 }))
module.exports = config;
My tsconfig.json looks like this:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmitHelpers": false,
"sourceMap": true
},
"filesGlob": [
"./app/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}
Can anyone suggest what might be happening? I don't seem to be able to produce any logs from either the webpack dev server or the npm build.
After hours of reverse-engineering ts-loader I finally found out what was causing this "freeze" (as it may seem) in my case:
I am building a web scraper and had amassed around 40Gb of cached data in a hashed directory structure between the previous, successful deployment and the now failing/freezing deployment.
Turned out, since I'd forgotten to include the root cache directory in the "exclude" option in my tsconfig.json, ts-loader was going through all sub-folders in the cache directory. So, it wasn't actually hanging, it was just looking through millions of files.
When I added the cache directory to the excluded files option, everything went back to normal.
Hope this helps you with your issue. In case you want to look into what's going on with typescript, I'd recommend to experiment with some console.logs in the visitDirectory-function in typescript.js. This was what finally helped me resolve this problem.
Cheers
Sam

Resources