I've created a MERN (MongoDB, ExpressJS, React, Node) project via express-generator (express myNewApp).
Inside a react component I have this piece of ES6 code
onChange = (event, { newValue }) => { // FYI this is line 53
this.setState({
value: newValue
});
};
When I run npm start I get this error: Module build failed: SyntaxError: Unexpected token (53:13).
Here's my package.json:{
"name": "myNewApp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "webpack --progress --colors --watch -d",
"build": "webpack --progress --colors -p"
},
"dependencies": {
"axios": "^0.15.3",
"babel-cli": "^6.11.4",
"babel-core": "^6.13.2",
"babel-preset-es2015": "^6.13.2",
"babel-preset-react": "^6.11.1",
"body-parser": "~1.16.0",
"cookie-parser": "~1.4.3",
"debug": "~2.6.0",
"ejs": "^2.5.6",
"express": "~4.14.1",
"jade": "~1.11.0",
"mongojs": "^2.4.0",
"morgan": "~1.7.0",
"react": "^15.4.2",
"react-autosuggest": "^9.3.2",
"react-bootstrap": "^0.30.7",
"react-dom": "^15.4.2",
"react-router": "^2.6.1",
"serve-favicon": "~2.3.2"
},
"devDependencies": {
"babel-loader": "^6.2.10",
"http-server": "^0.9.0",
"webpack": "^1.13.3"
}
}
My webpack config file looks like this.
var webpack = require('webpack');
var definePlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')),
__PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false'))
});
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');
module.exports = {
cache: true,
entry: { main: './views/index.jsx' },
output: { path: 'public/build', filename: '[name].js' },
module: {
loaders: [
{test: /\.jsx?$/, loader: 'babel', exclude: /(node_modules|bower_components)/, query: { presets: ['react', 'es2015'] }},
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: [
definePlugin,
commonsPlugin
]
};
npm i --save-dev babel-preset-stage-0
Change webpack.config.js: query: { presets: ['react', 'es2015', 'stage-0']
onChange = ... is a class property assignment, in order for your code to transpile using Babel, you need to npm install --save-dev babel-plugin-transform-class-properties, and then to invoke the plugin inside your .babelrc file, see here for full details.
Related
I made my own react component npm package and published in npm, now when import and use it in other CRA apps, i get this error when npm start in run in command line .
and in console:
My webpack.config.js file:
var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'web',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?limit=512&&name=[path][name].[ext]?[hash]'
}
]
},
mode: 'development',
externals: {
'react': 'commonjs react'
}
};
My package.json file:
{
"name": "primetable1",
"version": "1.0.0",
"description": "A Datatable for react apps based on Primereact",
"main": "build/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --watch",
"build": "webpack"
},
"keywords": [
"primereact",
"primeicons"
],
"author": "Anish Arya",
"license": "ISC",
"peerDependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-runtime": "^6.26.0",
"css-loader": "^3.4.2",
"file-loader": "^5.0.2",
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-hot-loader": "^4.12.19",
"react-scripts": "3.4.0",
"style-loader": "^1.1.3",
"webpack-cli": "^3.3.11",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {
"classnames": "^2.2.6",
"primeicons": "^2.0.0",
"primereact": "^3.4.0",
"react-transition-group": "^4.3.0"
}
}
My .babelrc file:
{
"presets": ["env"],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx",
"react-hot-loader/babel"
]
}
I followed this article to create and publish npm package:
https://codeburst.io/extracting-a-react-js-component-and-publishing-it-on-npm-2a49096757f5
How to solve this error?
The externals configuration seems wrong – you probably only need externals: [nodeExternals()] (from const nodeExternals = require("webpack-node-externals");).
I have a custom build setup for chrome extension which injects iframe to webpages, and this iframe is built using vue.js.
Entry point for building this iframe is src/popup/js and it should output to dist/popup.
This all works fine, but I don't know how to setup hot reload so I can see the changes in browser the moment I make changes in code.
Currently, when I run build step, everything is prepared and placed into dist folder, and iframe I want to hot reload is dist/popup/popup.html file.
This is my package.json:
{
"name": "extensionname",
"version": "1.0.17",
"description": "Chrome Extension",
"scripts": {
"lint": "eslint --ext .js,.vue src",
"prettier": "prettier \"src/**/*.{js,vue}\"",
"prettier:write": "npm run prettier -- --write",
"build-zip": "node scripts/build-zip.js",
"build:prod": "cross-env NODE_ENV=production TARGET_ENV=production webpack --hide-modules && cross-env NODE_ENV=production TARGET_ENV=production npm run build-zip",
"build:store": "cross-env NODE_ENV=production TARGET_ENV=store webpack --hide-modules && cross-env NODE_ENV=production TARGET_ENV=store npm run build-zip",
"build:dev": "cross-env NODE_ENV=development TARGET_ENV=development webpack --hide-modules && cross-env NODE_ENV=development TARGET_ENV=development npm run build-zip",
"build:test": "cross-env NODE_ENV=development TARGET_ENV=test webpack --hide-modules && cross-env NODE_ENV=development TARGET_ENV=test npm run build-zip"
},
"dependencies": {
"axios": "^0.18.0",
"emoji-mart-vue": "^2.6.6",
"moment": "^2.22.2",
"vue": "^2.6.10",
"vuetify": "^1.5.4",
"vuex": "^3.0.1",
"split-sms": "^0.1.7"
},
"devDependencies": {
"#babel/core": "^7.1.2",
"#babel/plugin-proposal-optional-chaining": "^7.0.0",
"#babel/preset-env": "^7.1.0",
"#types/chrome": "^0.0.74",
"archiver": "^3.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.2",
"copy-webpack-plugin": "^4.5.3",
"core-js": "^2.6.5",
"cross-env": "^5.2.0",
"css-loader": "^0.28.11",
"ejs": "^2.6.1",
"eslint": "^5.16.0",
"eslint-config-prettier": "^3.1.0",
"eslint-config-standard": "^12.0.0",
"eslint-friendly-formatter": "^4.0.1",
"eslint-loader": "^2.1.2",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-prettier": "^3.0.1",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^5.2.2",
"file-loader": "^1.1.11",
"mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.9.3",
"prettier": "^1.14.3",
"sass-loader": "^7.1.0",
"vue-loader": "^15.4.2",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
}
}
This is webpack.config.js :
const webpack = require('webpack');
const ejs = require('ejs');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const { version } = require('./package.json');
const config = {
mode: process.env.NODE_ENV,
context: __dirname + '/src',
entry: {
'popup/popup': './popup/popup.js',
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
},
resolve: {
extensions: ['.js', '.vue', '.json'],
},
module: {
rules: [
{
test: /\.vue$/,
loaders: 'vue-loader',
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
{
test: /\.sass$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader?indentedSyntax'],
},
{
test: /\.(png|jpg|gif|svg|ico)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?emitFile=false',
},
},
],
},
plugins: [
new webpack.DefinePlugin({
global: 'window',
'process.env.TARGET_ENV': JSON.stringify(process.env.TARGET_ENV)
}),
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css',
}),
new CopyWebpackPlugin([
{ from: 'images', to: 'images' },
{ from: 'scripts', to: 'scripts' },
{ from: 'css', to: 'css'},
{ from: 'popup/popup.html', to: 'popup/popup.html', transform: transformHtml },
{
from: 'manifest.json',
to: 'manifest.json',
transform: content => {
const jsonContent = JSON.parse(content);
jsonContent.version = version;
if (process.env.TARGET_ENV != 'store') {
jsonContent['content_security_policy'] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
jsonContent['key'] = '123456';
}
return JSON.stringify(jsonContent, null, 4);
},
},
{
from: 'config.json',
to: 'config.js',
transform: content => {
return transformConfigForExtension(content);
},
},
]),
],
};
if (config.mode === 'production') {
config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
]);
}
function transformHtml(content) {
return ejs.render(content.toString(), {
...process.env,
});
}
function transformConfigForExtension(content){
let extensionConfig = JSON.parse(content.toString())[process.env.TARGET_ENV];
return 'const config = ' + JSON.stringify(extensionConfig, null, 4);
}
module.exports = config;
And this is my project structure:
To the best of my knowledge, this is not possible on Chrome. Take a look at web-ext. It allows you to hot-reload code while developing an extension on Firefox.
Alternatively, you can also create your own extension that takes advantage of the management API to reload an extension. I'm guessing this is what web-ext does in the background.
I'm learning webpack 4. Is there a way to set custom entry and output, because no tutorial seems to explain that.
You can try the following link:
https://www.valentinog.com/blog/webpack-4-tutorial/#webpack_4_overriding_the_defaults_entryoutput
Quote from the link:
I love webpack 4 zero conf but how about overriding the default entry point? And the default output?
Configure them in package.json!
An example from the link:
"scripts": {
"dev": "webpack --mode development ./foo/src/js/index.js --output ./foo/main.js",
"build": "webpack --mode production ./foo/src/js/index.js --output ./foo/main.js"
}
Hope this helps.
You can configure entry and output in webpack.config.js. In example configuration below I have added entry as a string whereas you can add as an object and array as well and in a similar way you can add output key as a string, as follows:
var path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
},
mode: 'development',
entry: './app/main.js',
cache: true,
output: {
path: __dirname,
filename: './resources/script.js'
},
module: {
rules: [
{
test: path.join(__dirname, '.'),
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
presets: ['es2015', 'react']
}
}
]
}
};
Below is the package.json to work with npm dependencies:
{
"name": "reactjs",
"version": "1.0.0",
"description": "React Js",
"keywords": [
"react"
],
"author": "Arpit Aggarwal",
"dependencies": {
"axios": "^0.18.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
},
"scripts": {
"build": "webpack",
"watch": "webpack --watch -d"
},
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^7.1.4",
"babel-polyfill": "^6.16.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0"
}
}
I am very new to React and facing problem while following a tutorial. I was able to build and run output js file using webpack command, but I am not able to build it with webpack-dev-server. Can someone find out the mistake?
Here is the exact command I am using npm run dev. Below is the code.
IDE used: Visual Studio Code
Folder Structure:
Here in the structure, the build.min.js file under dist folder i have, is what I built running manually webpack command, but on running webpack-dev-server and changing any .js / .html file it is not rebuilding/reloading. Here are the configuration files.
Package.json
{
"name": "reacr-practice",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "./node_modules/.bin/webpack-dev-server --content-base src --inline --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.19.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-0": "^6.16.0",
"jquery": "^3.1.1",
"lodash": "^4.17.4",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack": "^1.14.0"
},
"devDependencies": {
"nodemon": "^1.11.0",
"webpack-dev-server": "^1.16.2"
}
}
Webpack.config.json
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
module.exports = {
context: __dirname + "/src",
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/app.js",
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy']
}
}
]
},
output: {
path: __dirname + "/src/dist",
filename: "build.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};`
When I run npm build nothing seems to happen. When I look for the build files I don't see anything. npm start works fine though.
Package.json
{
"name": "pro-react-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --progress",
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js --progress",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.10.4",
"babel-loader": "^6.2.4",
"babel-plugin-react-transform": "^2.0.2",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"html-webpack-plugin": "^2.22.0",
"json-loader": "^0.5.4",
"postcss-loader": "^0.9.1",
"precss": "^1.4.0",
"react-transform-hmr": "^1.0.4",
"style-loader": "^0.13.1",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"react": "^15.2.1",
"react-dom": "^15.2.1"
}
}
Webpack.production.config.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: __dirname + "/app/main.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.json$/,
loader: "json"
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css?modules!postcss')
}
]
},
postcss: [
require('autoprefixer')
],
plugins: [
new HtmlWebpackPlugin({
template: __dirname + "/app/index.tmpl.html"
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin("style.css")
]
}
I also have .babelrc file and webpack.config.js file, let me know if those would be useful to see as well, thanks.
Might be related to the fact that build is an internal command. Seems like I have had this happen to me as well in the past. Check out this Question
In order to run a custom script, you can use the npm run-script build or just npm run build. As stated in the NPM documentation