package.json scripts execution error (Webpack might be envolved) - javascript

I got the following lines in my package.json file (I just mirrored courses teacher)
"scripts": {
"build:dev": "env NODE_ENV=development webpack --config webpack.config.js",
"build:prod": "env NODE_ENV=production webpack --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
But unlike for him it doesn't work for me, when I point my mouse to a build word (both of them), and click "Run Script" I get this error:
Executing task: npm run build:dev
/usr/bin/bash: line 1: npm: command not found
* The terminal process "/usr/bin/bash '-c', 'npm run build:dev'" failed to launch (exit code: 127).
* Terminal will be reused by tasks, press any key to close it.
I certainly see no clues about that issue, and can't find them on the internet.
I have npm installed, and wondering what's wrong. Maybe webpack is bad configured, but If I just run
Webpack
in my console it compiles successfully. Anyway here is my webpack.config.js file:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const NODE_ENV = process.env.NODE_ENV;
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json']
},
mode: NODE_ENV ? NODE_ENV : 'development',
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
module: {
rules: [{
test: /\.[tj]sx?$/,
use: ['ts-loader']
}]
},
plugins: [
new HTMLWebpackPlugin({ template: path.resolve(__dirname, 'index.html') })
]
};
By the way, I have one problem in my project that may somehow affect mentioned problem (that isn't likely though). I've typed
tsc --init
to create tsconfig.json file and here is vscode problem warning:
`JSON schema for the TypeScript compiler's configuration file
Cannot write file '/home/timothy/Desktop/WEB_COURSE/dist/index.js' because it would overwrite input file.ts
Cannot write file '/home/timothy/Desktop/WEB_COURSE/dist/index.js' because it would overwrite input file.ts`
I didn't try to resolve this issue yet, because I really don't know what even should I do.

Related

Import root directory using babel-plugin-import is not working with Create-React-App

My .babelrc config is not working. I keep getting this error message.
Module not found: Can't resolve '#project/customTable' in...
I want to shorten importing paths.
Can someone help me fix this?
Current code: import customTable from "../../../customTable";
Goal: import customTable from "#project/customTable";
Below is my .babelrc file:
{
"plugins": [
["babel-plugin-root-import", {
"rootPathSuffix": "src",
"rootPathPrefix": "#project"
}]
]
}
Use Webpack alias
I'm not sure why your code ain't working. Everything seems to be fine. But, an alternative way would be to do this using Webpack aliases, like so:
modeule.exports = {
entry: [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs
],
resolve: {
alias: {
'#project': path.join(__dirname, '../src') // <--- Here
}
}
}
Q: But, I used create-react-app. I can't find webpack config files in my project directory? :(
A: Run npm run eject and you'll get all the webpack configurations in a config folder of your project directory. :)
Note: Don't forget to restart your application after making all these changes to reflect.
I suppose you are using react-script in your project. You have to know you cant change the Babel config directly. you can use
npm run eject
but it's not a recommended way because by ejecting you'll lose some features like TypeScript, Sass, CSS Modules, and more.
by the way, you can use customize-cra and react-app-rewired npm packages. first, install them:
npm install customize-cra react-app-rewired --dev
//or
yarn add customize-cra react-app-rewired --dev
and create a config-overrides.js file in the same level where your package.json has placed.
and put the below config in it:
const { override, addBabelPlugins } = require("customize-cra");
module.exports = override(
addBabelPlugins([
"babel-plugin-root-import",
{ rootPathSuffix: "./src", rootPathPrefix: "#/" },
])
);
last but not least you have to change all react-script to react-app-rewired in your package.json file like:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},

Splitting up project with react & webpack4; html tags are unexpected tokens

Background
I'm using react, babel, webpack4, and es6(or maybe es7)
I have some modules that are reused by multiple react projects. For this reason I've created a 'Standard' folder that contains these modules so that they are kept separate from any specific project.
Problem
In my react project I edited my webpack.config.js to contain
resolve: {
extensions: ['.css', '.js', '.jsx'],
alias: {
Standard: '/Path/To/Standard',
}
}
Then to import a module from it I call
import MyModule from 'Standard/MyModule.js'
When I do this, it looks like the html tags aren't recognized within the files in my Standard folder
Error Messages
For webpack-dev-server --inline
ERROR in /Path/To/Standard/MyModule.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Path/To/Standard/MyModule.js: Unexpected token (13:8)
11 | var MyModule = (props) => {
12 | return (
> 13 | <header id='Header' className={props.className}>
For webpack
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! default#1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the default#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Debugging attempts
I've tried to create a webpack.config.js and package.json inside my standard folder(in addition to my project folder), but nothing really seems to help
I tried some npm installs to install babel, because that seemed like the most obvious solution, and is used on this answer in an older webpack version, but I still get the same problems
npm install --save react
npm install --save babel #babel/cli #babel/core #babel/preset-env #babel/preset-react
npm install --save babel-core babel-loader babel-cli babel-preset-env babel-preset-react webpack
Also it looks like this post which is a reply to this blog might be related, but this solution didn't work for me.
package.json
{
"scripts": {
"webpack": "webpack",
"start": "http-server"
},
"dependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"#babel/plugin-proposal-object-rest-spread": "^7.5.1",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.5.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"webpack": "^4.28.0"
}
}
webpack.config.js
var webpack = require('webpack');
const config = {
mode: 'development', // set mode option, 'development' or 'production'
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
resolve: {
extensions: ['.css', '.js', '.jsx'],
}
}
module.exports = config;
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
You're 1st problem here is that babel is not parsing code from you're packages (error say that it try to exec not transpiled jsx code).
Maybe the babel presets is not accessible in you're package directory.
You can try copying them or set them directly in the webpack config
{
loader : 'babel-loader',
options: {
presets : [
['#babel/preset-env',
{// here the presets params
}],
'#babel/preset-react'
],
plugins : [
['#babel/plugin-proposal-class-properties', {
"loose": true
}]
]
}
},
Possibly the exclude regexp of babel exclude the packages from where you want importing scripts :
exclude: /(node_modules|bower_components)/,
So you can use a custom function like that :
exclude: {test:(pathName)=>(isInternalCode(pathName))),
Or use negative lookahead in the reg exp like :
/(node_modules(?!\b(?:OneFolder|AnotherIncluded))|bower_modules)/
That's said the usual way is to compile independently you're packages ( by externalizing all theirs deps from the builds & adding them to "peerDependencies" or "dependencies" )
Also; there a plugin to make "inheritable" packages; layer-pack.
It allow making "inheritable" projects, & deal with node_modules & webpack to make inheritable "code layers" & even work when compiling node scripts or using monorepo structure
Using it you can simply put you're components in a shared inheritable package
it come with some nice features like glob resolving, which help including an unknown number of files.
There is samples here & doc here
Hope it help :)

Does "--content-base" is deprecated from webpack-dev-server while using webpack v2.2?

I started migrating webpack 2.2 here i'm facing issue while configuring webpack-dev-server,my build script is
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/"
Getting below error
ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src/app/index.js content-base ./src
Module not found: Error: Can't resolve 'content-base' in 'E:\React\react-basics'
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/app/index.js content-base ./src
ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src/app/index.js content-base ./src
Module not found: Error: Can't resolve 'E:\React\react-basics\src' in 'E:\React\react-basics'
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/app/index.js content-base ./src
webpack: Failed to compile.
where as if i set my script without content-base works properly
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server
Why this error occurs how to set webpack-dev-server for webpack 2.2?
I suggest you to configure the devServer settings in the webpack config file:
Example:
devServer: {
// All options here: https://webpack.js.org/configuration/dev-server/
// enable HMR on the server
hot: true,
// match the output path
contentBase: resolve(__dirname, '../dist'),
// match the output `publicPath`
publicPath: '/',
// Enable to integrate with Docker
//host:"0.0.0.0",
port: 3000,
historyApiFallback: true,
// All the stats options here: https://webpack.js.org/configuration/stats/
stats: {
colors: true, // color is life
chunks: false, // this reduces the amount of stuff I see in my terminal; configure to your needs
'errors-only': true
}
},
And you could invode webpack-dev-server from package.json like here:
"start": "set NODE_ENV=development && webpack-dev-server --open --config ./webpack/webpack.config.dev.js",

webpack -p fails to uglify es2015 code

The webpack -p cli command fails to uglify es2015 code
package.json
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.2"
}
webpack.config.js
var webpack = require("webpack");
var config = {
entry: './src/app.js',
devtool: "source-map",
output: {
path: '../Scripts',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
},
include: ["./src"],
exclude: /node_modules/
}
]
}
}
module.exports = config;
Error when running webpack -p
ERROR in bundle.js from UglifyJs
Unexpected character '`' [./src/LineEndRenderer.js:33,0]
(es2015 template string use)
Running webpack -d works fine.
A user (fulls1z3) at github came up with a solution that does not require babel (see post from 11/26/2016):
Here is a copy:
webpack#2 users, I'm hereby trying to help by providing detailed instructions to use the Harmony branch of UglifyJs2 with webpack:
Fork webpack,
On that fork, delete all branches except master,
Clone master branch to a local folder,
On the local folder, delete all files,
Commit the empty local folder,
Download the latest release (ex: v2.1.0-beta.27 at the moment)
Extract contents of zip file to the local folder,
On the local folder, edit forked package.json, change
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
to point UglifyJs2 (harmony branch) dependency to that branch.
Commit changes,
Finally, point webpack in your package.json to your custom fork:
"webpack": "[USERNAME]/webpack#master"
OR,
Point webpack in your package.json to fulls1z3/webpack (ES6/ES2015 friendly webpack fork):
"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"
I was using webpack globally, so I had to run this too:
npm install yargs supports-color enhanced-resolve interpret tapable webpack-sources source-map uglify-js object-assign async loader-runner acorn watchpack mkdirp ajv ajv-keywords node-libs-browser -g
Then I replaced my global webpack npm folder with webpack-2.1.0-beta.27-harmony.zip from https://github.com/fulls1z3/webpack/releases
Lastly, I replaced my global uglify-js npm folder with UglifyJS2-harmony.zip from https://github.com/mishoo/UglifyJS2/tree/harmony

Webpack does not generate bundle file on npm run

Greetings one and all,
After having made a React application, I decided to dive in deeper into Webpack.
I am rather new at the whole npm automation scene and after having followed a cookbook and various tutorials, I just cannot let npm run dev bundle my application. It generates a bundle.js perfectly fine when I run webpack, but what appealed to me was having webpack generate a physical file whenever I change something. Gulp and Grunt can do this for me, but I'd like to get it to work with webpack as well.
So, without further ado, some code. I run npm run dev which is defined like so (package.json, just the scripts part*):
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
}
With the following Webpack configuration:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/js/main.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: '/js/bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
], ["normal"], "loader")
]
};
Cases:
webpack: Bundles my application into dist/js/bundle.js perfectly fine.
webpack-dev-server: Seems to stream a memory bundle from my JS perfectly fine, but does not generate a bundle on disk.
npm run dev: Starts the webpack server, but does not result in a bundle, nor does my application run, resulting in a Cannot GET/ error.
Can anyone point me in the right direction? I have tried variations on the config, but to no avail.. And just to be complete, I will show my directory structure:
./project
./dist
./js
./bundle.js
./src
./js
./main.js
./package.json
./webpack.config.js
Once again, thanks for the assist!
It is due to wrongly written scripts in package.json file. Replace your scripts with the below. It is because you are not providing the correct path to your bundle.js file which is need to be create. "-p" means to read the entry and output keys of webpack.config.js. Then run this cmd: $ npm run build
"scripts": {
"build": "webpack -p",
"dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
}
For me the problem was with package.json under that "scripts"
Here is the fix:
Inside your package.json file, under script add the following:
"scripts": {
"start": "webpack-dev-server",
"build": "webpack -p"
}
First I ran the build then start.
yarn build
if you first build then your bundle.js file will be created and after that you can use this command:
yarn start
Instead of yarn, you can also use npm

Categories

Resources