Run cmd/terminal command on run in visual studio - reactjs

Background
I'm creating a small project in Visual Studio to learn React. However when I change something in my app.tsx, I have to run the
node_modules\.bin\webpack app.tsx --config webpack-config.js
command for my project to re-run the webpack so i can build and run my changed code.
There must be a better way to do this right?
What I want to do
I want to know if there is a way to automatically run this command when I press the run button in Visual Studio. Or if there is a better way of doing this, know how to simplify this process.
When I've done other javascript projects I've used vagrant or a build server that has been automated for this purpose (check code for changes, update the "converted/build/compile" code). But those processes have been automated from the start and not by me so I don't really know what to do.
What I've tried
Since I've never encountered a situation where this was an issue, I don't really know how to address this problem. I have searched for ways to "auto-run commands in the cmd/terminal on run" and similar search strings, but they all lead to solutions to problems other than this.
Question
How can I configure VS/implement a code snippet that runs the
node_modules\.bin\webpack app.tsx --config webpack-config.js
command in the cmd/terminal when I press Run in Visual Studio?
EDIT:
I have solved the problem.
It says on their official docs that the feature I need is "watch" and it says that this feature is:
In webpack-dev-server and webpack-dev-middleware watch mode is enabled by default.
But it is not. So in order to enable it I had to add a line to the webpack-config.js with watch:true
The now working config looks like this:
module.exports = {
devtool: 'source-map',
entry: "./app.tsx",
mode: "development",
output: {
filename: "./app-bundle.js"
},
resolve: {
extensions: ['.Webpack.js', '.web.js', '.ts', '.js', '.jsx', '.tsx']
},
module: {
rules: [
{
test: /\.tsx$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'ts-loader'
}
}
]
},
watch:true
}
Now I only have to run the command once and it checks for changes in my project code and re-packs the webpack automatically.

Related

rollup bundled react development resources

I'm using "vite": "^2.8.6" for React project. What I know is that Vite is using Rollup as module bundler, but I stumbled on a problem where Rollup still bundling my react-dom.development.js and react.development.js. I've used "rollup-plugin-replace" to replace my 'process.env.NODE_ENV' to production, but the problem still occur. Here is the my rollup config:
rollupOptions: {
// https://reactjs.org/docs/optimizing-performance.html#rollup
plugins: [
rollupPluginReplace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
rollupPluginCommonjs(),
terser(),
visualizer()
],
},
When I analyze with rollup-visualizer, you can see that rollup bundled both production and development dependency, which supposedly only bundled one of them right?
The problem with this is that there is extra 1MB of dead code in the bundle, it will be great if I can eliminate it.
This generally means that rollup does not understand that your app is directed towards production code. In my case it was because I had set up library mode.
lib: {
entry: './src/app.ts',
fileName: 'app.ts',
name: 'AppClass',
formats: ['iife'],
}
Removing this block finally generated a build which was sane in size. For more information, see the vite documentation.
If you were also trying to get vite/rollup to build your app as an IIFE, setting rollupOptions worked for me:
rollupOptions: {
output: {
entryFileNames: `[name].js`,
assetFileNames: `app.[ext]`,
format: 'iife',
},
input: ['./src/app.ts'],
},

React - Styling not being compiled when running npm run build

For the first time I've ran npm run build and uploaded to my server.
I realised that there wasn't any styling being pulled through very quickly and that it isn't even being referenced in my index.html file.
This is all working great on my dev setup when I run npm start
This is my production config and I'm wondering if there is anything obvious to why this isn't running.
https://jsfiddle.net/vmt20f8w/
I should point out that I am using SCSS files instead of css and importing them into my component js files. I thought the webpack.config.prod.js would have then taken all of these scss files and compile them down to one css file?
Update
I've now updated my config with the below code and it still isn't compiling the scss.
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
}]
},
To make this even more clear I've actually got a public repo in which people can view all my code to understand the problem:
https://github.com/maximus-lynn/react-portfolio
You are using a loader for css files, but not for your scss files. Install sass-loader and change your config to look something like this:
test: /\.scss/,
loader: 'style-loader!css-loader!sass-loader'

workbox not picking up in-memory files with webpack-dev-server

In our project we are using webpack-dev-server to run our development environment.
We are currently transforming the project into a progressive-web-app using workbox.
When we run webpack with NODE_ENV=production everything is working fine, as it first compiles the files, and then the workbox plugin picks them up and adds them to the service-worker.
When we run webpack-dev-server hot, the build fails when running the workbox plugin as it cannot find any files in the dist folder.
The problem seems to be that workbox is not picking up the js and css files that are generated in-memory and seems to need the files on the file system.
module.exports = {
context: path.resolve(__dirname, 'front'),
entry: [
...preEntries,
'./react/app.js'
],
output: {
path: path.resolve(__dirname, 'front-dist'),
filename: `react/app.${git.gitCommitAbbrev}.js`,
chunkFilename: `react/[id].app.${git.gitCommitAbbrev}.js`,
publicPath: '/glass/'
},
devtool: isProdEnv ? false : 'eval-source-map',
stats: {
chunkModules: false
},
module: {
...
},
plugins: [
new WorkboxPlugin({
globDirectory: path.resolve(__dirname, 'front-dist'),
globPatterns: ['**/*.{html,js,css,woff2}'],
swDest: path.join(path.resolve(__dirname, 'front-dist/sw/'), 'service-worker.js'),
handleFetch: true,
clientsClaim: true,
skipWaiting: true,
})
]
}
Any idea's as to how this should be working
Recent releases of workbox-webpack-plugin have support for in-memory filesystems, with coverage in its test suite.
If you're still having troubles with the current release of Workbox, please open an issue on the issue tracker and we can investigate further.
That being said, using a cache-first service worker inside of a hot-reload, local development environment is a puzzling choice, as caching defeats the purpose of seeing updates right away.

Syntax Error In IE 11 for this node_moduels

I am getting a syntax error in IE when this component of react is loaded in the webpage. Has anybody got the same problem? This is an inherited package, and a syntax error from node_modules makes no sense?
"use strict";
/* WEBPACK VAR INJECTION */(function(module) {
const colorConvert = __webpack_require__(/*! color-convert */ "./node_modules/color-convert/index.js");
const wrapAnsi16 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${38 + offset};5;${code}m`;
};
If you are using newer versions of Node/NPM, check your package.json file -> "browserslist" section.
This is the default "browserslist" created for you if you do not have one defined:
In this case, if you run "npm start" on your LOCAL Environment, Babel will not create Polyfills for IE11 because its not included as a target browser in "development". To get this working, I deleted my node_modules directory completely, ran 'npm install', updated package.json with:
and ran 'npm start.
The reason why this fails is that babel or your other favorite transpiler might ignore node_modules (if that's how its configured), so you need to include it manually because IE does not support arrow function syntax.
First, if you search for wrapAnsi16 or wrapAnsi256 function names online it'll point you to common npm packages, such as: ansi-styles, chalk or color-convert, debug, strip-ansi, etc.
If you are using Webpack you can add the following to your rules:
module: {
rules: [{
exclude: /node_modules\/(?!(color-convert|ansi-styles|strip-ansi|ansi-regex|debug|react-dev-utils|chalk)\/).*/
}]
}
or, easier to read:
module: {
rules: [{
include: [
path.resolve(__dirname, 'node_modules/ansi-styles'),
path.resolve(__dirname, 'node_modules/strip-ansi'),
... other's here...
path.resolve(__dirname, 'src'),
]
}]
}
Hope this helps somebody in the future ;)
TLDR; you don't need this library, just run
npm run build
And it will be excluded from your build.
I have same problem with create-react-app, and I solve it (no). From my discovery, this library should not appear in browser, because it was designed for nodejs environment. Also I found, this library come to me as dependency of jest, and jest is dependency for tests and it come as dependency for react.
So, I run
npm run build
server -s build
And try my application in IE. And it work. So, when you run
npm start
It make file including dev dependencies and other garbage that should not appear in production and in browser at all. When you run
npm run build
It make file only with required project libraries.
I had similar issue #punkbit solution and installing 'react-app-polyfill'
and importing it at the top of the index.js file solved it
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
If it still does not work delete node-modules and reinstall also clear cache in IE.
All the best :)
This problem occurs because your compiled code contains (modern) ES6 syntax whilst IE11 only supports ES5.
A way to fix this is to instruct webpack to specifically compile the mentioned packages into ES5;
module: {
rules: [{
test: /\.(tsx?|js)$/,
include: [
// These dependencies have es6 syntax which ie11 doesn't like.
// Whenever you see a "SyntaxError" that crashes IE11 because of a new lib, add it here.
path.join(__dirname, 'node_modules/react-intl'),
path.join(__dirname, 'node_modules/pkce-challenge'),
path.join(__dirname, 'node_modules/fuse.js')
],
use: [{
loader: 'ts-loader', // Or whatever loader you're using
}]
}]
}
for me this was: fuse.js, pkce-challenge and react-intl.

Debugging ES6 mdules in browser

I have a large angular 1.6 application. Most of it is written in ES5 syntax and some small parts are sort of ES6. I'm saying sort of ES6 because we don't actually use modules/import/export. The reason for that is although we do use gulp to bundle all source code when deploying, we don't want to do that on dev, because it involves running gulp every small code change, and running it takes time, plus the fact that its much nicer to debug the original file per class structure rather then the bundled code (even when not uglified).
Is there a way, to debug angular 1.6 in ES6 syntax without bundling? Can Babel somehow help me keep the original files structure, for development purposes only?
Babel is basically a transpiler, so its job is only to make sure to output es5 code. It will NOT help u organize folder structure.
Bundling it with webpack helps u maintain a sane folder structure. u can have a configuration object which specifies your entry-point,(called "entry"), output-file, loaders, inline : true, so it automagically refreshes the browser for you for any small change. webpack also comes with a dev-server.
Below is what i use in my webpack.config.js.
It helps me maintain a local sandbox for my es6 escapades.
module.exports = {
entry : ['./app/index.js'], //entrypoint
output: {
path: 'D:\\js\\es6\\build',
filename: 'bundle.js'
},
module: {
loaders: [ //specify objects for each loader
{
loader: 'babel-loader' ,
test: /\.js$/,
exclude: /node_modules/, //we dont want to transpile the .js on node_modules
}
]
},
devServer: {
port: 3000,
contentBase: './build',
inline: true, //allows us to run automatic live code update
}
}

Resources