I am building a React app from scratch using webpack and babel. I have all the rules, babel configurations in place. I have setup my application with three config files for webpack:
dev config
prod config
common items across both configs (rules, variables, aliases etc).
When I am trying to start my application locally (development) using webpack-dev-server, I get an error on line import merge from 'webpack-merge'
Command used : webpack-dev-server --config webpack.config.dev.babel.js --open
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at WEBPACK_OPTIONS (C:\Users\hp-pc\node_modules\webpack-cli\bin\convert-argv.js:115:13)
at requireConfig (C:\Users\hp-pc\node_modules\webpack-cli\bin\convert-argv.js:117:6)
at C:\Users\hp-pc\node_modules\webpack-cli\bin\convert-argv.js:124:17
at Array.forEach (<anonymous>)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I am not able to figure out where the issue is exactly
Possible fixes that I tried :
Deleting node_modules and doing a fresh install.
Updating all dependencies using yarn-upgrade-all.
Setting a react project with webpack and babel from scratch.
SO Answer.
Adding "type":"module" to package.json.
None of these have worked for me so far. Can anyone please guide me on how to resolve this issue?
Here are a few files which might help troubleshoot this further :
package.json
{
"name": "weather-app",
"version": "0.0.1",
"private": true,
"dependencies": {
"autoprefixer": "^10.2.5",
"axios": "^0.21.1",
"classnames": "^2.3.1",
"copy-webpack-plugin": "^8.1.0",
"dotenv": "^8.2.0",
"git-revision-webpack-plugin": "^3.0.6",
"html-webpack-plugin": "^5.3.1",
"mini-css-extract-plugin": "^1.4.0",
"moment": "^2.29.1",
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-debounce-input": "^3.2.3",
"react-dom": "^17.0.2",
"react-redux": "^7.2.3",
"react-router-dom": "^5.2.0",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0"
},
"devDependencies": {
"#babel/cli": "^7.13.14",
"#babel/core": "^7.13.14",
"#babel/node": "^7.13.13",
"#babel/plugin-transform-modules-commonjs": "^7.13.8",
"#babel/plugin-transform-regenerator": "^7.12.13",
"#babel/plugin-transform-runtime": "^7.13.10",
"#babel/preset-env": "^7.13.12",
"#babel/preset-flow": "^7.13.13",
"#babel/preset-react": "^7.13.13",
"#babel/register": "^7.13.14",
"babel-loader": "^8.2.2",
"babel-plugin-react-display-name": "^2.0.0",
"babel-plugin-webpack-alias": "^2.1.2",
"babel-preset-react-hmre": "^1.1.1",
"case-sensitive-paths-webpack-plugin": "^2.4.0",
"chai": "^4.3.4",
"chalk": "^4.1.0",
"css-loader": "^5.2.0",
"enzyme": "^3.11.0",
"eslint": "^7.23.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.1",
"node-sass": "^5.0.0",
"terser-webpack-plugin": "^5.1.1",
"webpack": "^5.30.0",
"webpack-cli": "^4.6.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3",
"webpack-notifier": "^1.13.0"
},
"scripts": {
"start:dev": "webpack-dev-server --config webpack.config.dev.babel.js --open",
"start:mock": "nodemon mockAPI.js",
"update:packages": "node wipe-dependencies.js && rm -rf node_modules && npm update --save-dev && npm update --save"
},
"lint-staged": {
"*.js": [
"eslint --fix",
"git add"
]
},
"nyc": {
"exclude": [
"**/*.spec.js",
"dist",
"docs",
"helpers",
"node_modules",
"styleguide",
"webpack*"
],
"extensions": [
".js",
".jsx"
]
}
}
webpack.config.dev.babel.js
/* eslint-disable import/no-extraneous-dependencies */
import merge from 'webpack-merge';
import Notifier from 'webpack-notifier';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import common from './webpack.common';
module.exports = merge(common, {
mode: 'development',
devtool: 'source-map',
devServer: {
contentBase: './app/src',
historyApiFallback: true,
},
plugins: [
new Notifier(),
new CaseSensitivePathsPlugin(),
],
});
webpack.common.js
import path from 'path';
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import GitRevisionPlugin from 'git-revision-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
const gitRevisionPlugin = new GitRevisionPlugin();
const buildDateTime = new Date().toISOString();
const htmlConfig = {
template: 'index.html',
filename: 'index.html',
inject: true,
data: {
__VERSION__: JSON.stringify(gitRevisionPlugin.version()),
__COMMITHASH__: JSON.stringify(gitRevisionPlugin.commithash()),
__BRANCH__: JSON.stringify(gitRevisionPlugin.branch()),
__BUILDDATETIME__: buildDateTime,
},
};
module.exports = {
context: path.resolve(__dirname, './app/src'),
entry: {
app: ['./index.jsx'],
},
output: {
path: path.resolve(__dirname, './app/dist'),
publicPath: '/',
filename: '[name].[chunkhash].js',
},
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader?name=assets/fonts/[name].[ext]',
],
},
{
test: /(\.js|\.jsx)$/,
loader: 'babel-loader',
exclude: [/node_modules/],
include: [path.resolve(__dirname, './node_modules/react-icons/fa'), path.resolve(__dirname, './node_modules/react-onclickoutside')],
query: {
presets: [['#babel/env',
{
useBuiltIns: 'usage',
corejs: 3,
},
],
'#babel/react',
'#babel/flow'],
plugins: ['#babel/plugin-syntax-dynamic-import', '#babel/plugin-transform-regenerator', '#babel/plugin-proposal-class-properties', '#babel/plugin-transform-runtime', 'transform-class-properties'],
},
},
{
test: /\.(png|jpg|svg|ico)$/,
loader: 'file-loader',
},
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}),
new HtmlWebpackPlugin(htmlConfig),
],
resolve: {
alias: {
Actions: path.resolve(__dirname, 'app/src/actions'),
Components: path.resolve(__dirname, 'app/src/components/'),
Containers: path.resolve(__dirname, 'app/src/containers/'),
Helpers: path.resolve(__dirname, 'helpers/'),
Selectors: path.resolve(__dirname, 'app/src/selectors/'),
Utils: path.resolve(__dirname, 'app/src/utils'),
Assets: path.resolve(__dirname, 'app/src/assets'),
Apis: path.resolve(__dirname, 'app/src/api'),
},
extensions: ['.js', '.jsx', '.json', '*'],
},
};
.babelrc
{
"presets": [
"#babel/env",
"#babel/preset-react",
"#babel/preset-flow"
],
"env": {
"test": {
"plugins": [
"#babel/plugin-transform-regenerator",
"#babel/plugin-syntax-dynamic-import",
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
[
"module-resolver",
{
"alias": {
"Actions": "./app/src/actions",
"Assets": "./app/src/assets",
"Components": "./dims-common-ui/components/",
"Containers": "./app/src/containers",
"Helpers": "./helpers",
"Selectors": "./app/src/selectors",
"Utils": "./app/src/utils",
"Apis": "./app/src/api"
}
}
],
"#babel/plugin-proposal-class-properties"
]
}
}
}
On the webpack-merge readme, there are no examples using the pattern you used. Where did you see this? Have you tried to emulate the pattern of the docs? What I think this means is you define your config externally, and then run a function who returns the merge. Have you tried this?
module.exports = env => {
switch(env) {
case 'development':
return merge(commonConfig, developmentConfig);
case 'production':
return merge(commonConfig, productionConfig);
default:
throw new Error('No matching configuration was found!');
}
}
you need to tell babel what it needs to transpile and you do so with #babel/register so at yow entry point you need some like this
module.exports ={
entry: [
"#babel/register",
"path-to-where-your-entry-is-at"
]
}
So, the solution that worked for me was using webpack 4 instead of webpack as there seems to be some issue with webpack 5 and babel 7 in my use case. Thanks for your answers Ernesto and IWI!
Related
I am trying to setup a react app with latest versions.
React 17, Webpack 5 and other modules.
I need css modules with styleName concept by using babel-plugin-react-css-modules
Trying to run the code shows the output but no styles are applied.
package.json
{
"name": "react-app",
"version": "1.0.0",
"description": "React Template App",
"author": "",
"license": "ISC",
"main": "index.js",
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production",
"format": "prettier --write \"src/**/*.js\"",
"eslint-fix": "eslint --fix \"src/**/*.js\""
},
"dependencies": {
"babel-plugin-react-css-modules": "^5.2.6",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.1",
"eslint": "^7.16.0",
"eslint-config-react": "^1.1.7",
"eslint-loader": "^4.0.2",
"eslint-plugin-react": "^7.21.5",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.0",
"less": "^4.0.0",
"less-loader": "^7.2.0",
"mini-css-extract-plugin": "^1.3.3",
"prettier": "2.2.1",
"style-loader": "^2.0.0",
"webpack": "^5.11.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname, "dist"),
open: true,
host: "localhost",
compress: true,
port: process.env.CLIENT_PORT,
hot: true,
quiet: false
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.css$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
// "less-loader",
{
loader: 'css-loader',
options: {
modules: true,
}
}
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
favicon: "./public/favicon.ico"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
devtool: 'inline-source-map',
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
home.js
import React from "react";
import "./style.css";
const Home = () => {
return (
<div styleName="container">
<div styleName="title">Hello from Home CSS</div>
</div>
);
};
export default Home;
style.css
.container {
display: flex;
flex-direction: column;
}
.title {
font-size: 24px;
color: red;
}
That's interesting issue which requires us to do a few more things to make it work as following:
babel-plugin-react-css-modules isn't working properly with css-loader in case of generating the name. But luckily we have a work around by using a temporary fix of someone #dr.pogodin/babel-plugin-react-css-modules. So just install needed packages:
npm i -D #dr.pogodin/babel-plugin-react-css-modules postcss // postcss is required aslo
Reconfigure babel configuration by changing the name in .babelrc:
{
// ...
"plugins": [
[
"#dr.pogodin/babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
Finally, we would change the class name to make it consistent between babel-plugin-react-css-modules and css-loader in webpack.config.js:
{
test: /\.css$/,
use: [
// ...
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[path]___[name]__[local]___[hash:base64:5]', // This pattern matches with the default in `babel-plugin-react-css-modules`
},
}
}
],
}
My work is making a React UI Kit/Component Library to be used internally for our products. Everything is working fine while developing and displaying on Storybook.
While testing the library in a generic project out-of-the-box from create-react-app, importing and implementing the components made without React Hooks are alright, but soon as we use the ones made with Hooks - the Invalid Hook Call error shows: https://reactjs.org/warnings/invalid-hook-call-warning.html
Have tried everything listed there(and read and tried the github thread solutions linked on the page), and the component simply used useRef() and nothing else so we know no rules were broken, React and React-dom versions are up to date, and running npm ls react and npm ls react-dom in the project results in react#16.10.2 and react-dom#16.10.2 and nothing else... So it doesn't seem like we have multiple React's?
Any help would be much appreciated!!
This is the UI Kit's package.json
{
"name": "react-ui-kit",
"version": "0.0.15",
"description": "UI Kit",
"main": "dist/index",
"module": "dist/index",
"typings": "dist/index",
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/setupTests.js"
],
"coverageReporters": [
"json-summary",
"text",
"lcov"
]
},
"scripts": {
"test": "jest --coverage",
"test:badges": "npm run test && jest-coverage-badges input './coverage/coverage-summary.json' output './badges'",
"test-update": "jest --updateSnapshot",
"lint:css": "stylelint './src/**/*.js'",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook -c .storybook -o .out",
"generate": "plop --plopfile ./.plop/plop.config.js",
"build": "webpack --mode production",
"prepare": "npm run build",
"prepublishOnly": "npm run test:badges",
"storybook-docs": "build-storybook --docs",
"todo": "leasot './src/**/*.js'",
"todo-ci": "leasot -x --reporter markdown './src/**/*.js' > TODO.md"
},
"license": "ISC",
"peerDependencies": {
"prop-types": "^15.7.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"recharts": "^1.7.1",
"styled-components": "^4.3.2",
"styled-normalize": "^8.0.6"
},
"devDependencies": {
"#babel/cli": "^7.6.0",
"#babel/core": "^7.6.0",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/preset-env": "^7.6.0",
"#babel/preset-react": "^7.0.0",
"#storybook/addon-actions": "^5.2.1",
"#storybook/addon-docs": "^5.2.1",
"#storybook/addon-info": "^5.2.1",
"#storybook/addon-knobs": "^5.2.1",
"#storybook/addon-links": "^5.2.1",
"#storybook/addon-viewport": "^5.2.1",
"#storybook/addons": "^5.2.1",
"#storybook/react": "^5.2.1",
"babel-eslint": "^10.0.3",
"babel-jest": "^24.9.0",
"babel-loader": "^8.0.6",
"babel-plugin-styled-components": "^1.10.6",
"eslint": "^6.5.1",
"eslint-plugin-react": "^7.15.0",
"eslint-plugin-react-hooks": "^2.1.1",
"jest": "^24.9.0",
"jest-coverage-badges": "^1.1.2",
"jest-styled-components": "^6.3.3",
"leasot": "^8.2.0",
"plop": "^2.4.0",
"polished": "^3.4.1",
"prop-types": "^15.7.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-test-renderer": "^16.9.0",
"recharts": "^1.7.1",
"storybook-styled-components": "github:merishas/storybook-styled-components",
"styled-components": "^4.4.0",
"styled-normalize": "^8.0.6",
"stylelint": "^10.1.0",
"stylelint-config-recommended": "^2.2.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.8.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9"
},
"files": [
"dist"
],
}
The UI Kit's webpack.config.js
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index.js',
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: 'babel-loader',
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
limit: 10000,
mimetype: 'application/font-woff',
},
},
],
},
],
},
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components/'),
utils: path.resolve(__dirname, 'src/utils/'),
themes: path.resolve(__dirname, 'src/themes/'),
},
extensions: ['.js', '.jsx'],
},
devtool: false,
};
How components are imported and implemented in project:
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { FieldLabel, Button } from "react-ui-kit";
function App() {
return (
<div className="App">
<FieldLabel>THIS IS THE ONE USING the useRef Hook</FieldLabel>
<Button>This component is totally fine without FieldLabel, this isn't using Hooks</Button>
</div>
);
}
export default App;
Looking at the webpack config, I could see that, UI kit is getting bundled with react included which might be causing the issue.
To avoid this you could use webpack externals.
https://webpack.js.org/configuration/externals/
The externals configuration option provides a way of excluding
dependencies from the output bundles. Instead, the created bundle
relies on that dependency to be present in the consumer's environment.
This feature is typically most useful to library developers, however
there are a variety of applications for it.
So you could update UI Kit webpack config to not include react and the peerDependencies should take care of the dependency handling for any consumers of the library.
Updated webpack.config
const path = require("path");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
path: path.resolve("dist"),
filename: "index.js",
libraryTarget: "commonjs2"
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: "babel-loader"
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[ext]",
limit: 10000,
mimetype: "application/font-woff"
}
}
]
}
]
},
resolve: {
alias: {
components: path.resolve(__dirname, "src/components/"),
utils: path.resolve(__dirname, "src/utils/"),
themes: path.resolve(__dirname, "src/themes/")
},
extensions: [".js", ".jsx"]
},
externals: {
// Use external version of React
react: "react"
},
devtool: false
};
I have published a test package to confirm this (react-ui-kit-dontuse).
Demo links
v0.0.21(Without webpack externals)
https://stackblitz.com/edit/react-xyjgep
v0.0.23(With webpack externals)
https://stackblitz.com/edit/react-ihnmrl
Source code of test package: https://github.com/nithinthampi/react-ui-lib-test
Hope this helps!
I would like to generate source maps for our production build with Webpack. I managed to generate it, but when I stop on a breakpoint in the debugger, variables are not resolved:
What am I doing wrong? How can I generate a source map that lets the chrome devtools resolve the variables once I stopped on a breakpoint in the debugger?
These are my webpack configurations:
webpack.config.js:
const path = require('path');
const ROOT = path.resolve( __dirname, 'src/main/resources/packedbundle' );
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
context: ROOT,
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'eslint-loader',
options: {
failOnError: true,
quiet: true
}
}
],
enforce: 'pre'
},
{
test: /\.ts$/,
exclude: [ /node_modules/ ],
use: [
'ng-annotate-loader',
'awesome-typescript-loader'
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader'],
publicPath: '../'
}),
},
{
test: /\.(jpg|png|gif)$/,
use: 'file-loader'
},
{
test: /\.(svg|woff|woff2|eot|ttf)$/,
use: 'file-loader?outputPath=fonts/'
},
{
test: /.html$/,
exclude: /index.html$/,
use: 'html-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'AngularJS - Webpack',
template: 'index.html',
inject: true
}),
new LoaderOptionsPlugin({
debug: true
}),
new ExtractTextPlugin('css/style.css')
],
entry: './index.ts'
};
webpack-prd.config.js:
const path = require('path');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.config.js');
const DESTINATION = path.resolve( __dirname, 'dist/packedbundle' );
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = webpackMerge(commonConfig, {
devtool: 'module-source-map',
mode: 'production',
output: {
path: DESTINATION,
filename: 'js/[name]-bundle-[chunkhash].js'
},
optimization: {
minimizer: [
new UglifyJsPlugin({
sourceMap: true
})
]
}
});
package.json:
{
"name": "com.avon.maps.packedbundle.webcontent",
"version": "1.0.0",
"description": "Packed bundle creation screen frontend",
"main": "index.js",
"scripts": {
"prestart": "rimraf dist",
"start": "node node/node_modules/npm/bin/npx-cli.js check-node-version --package && webpack --config webpack-dev.config.js",
"prebuild": "rimraf dist",
"build": "node node/node_modules/npm/bin/npx-cli.js check-node-version --package && webpack --config webpack-prd.config.js",
"test": "mocha -r ts-node/register -r ignore-styles -r jsdom-global/register __tests__/**/*.spec.ts"
},
"author": "BlackBelt",
"private": true,
"engines": {
"node": "11.10.0"
},
"devDependencies": {
"#types/angular": "1.6.51",
"#types/angular-loading-bar": "0.0.35",
"#types/chai": "4.1.7",
"#types/core-js": "2.5.0",
"#types/jquery": "3.3.29",
"#types/kendo-ui": "2019.1.1",
"#types/mocha": "5.2.6",
"#types/node": "10.12.0",
"#types/underscore": "1.8.13",
"#types/webpack-env": "1.13.6",
"#typescript-eslint/eslint-plugin": "1.6.0",
"#typescript-eslint/parser": "1.6.0",
"acorn": "6.1.1",
"awesome-typescript-loader": "5.2.1",
"chai": "4.2.0",
"check-node-version": "3.2.0",
"css-loader": "1.0.0",
"eslint": "5.16.0",
"eslint-config-airbnb-base": "13.1.0",
"eslint-loader": "2.1.2",
"eslint-plugin-import": "2.16.0",
"extract-text-webpack-plugin": "v4.0.0-beta.0",
"file-loader": "2.0.0",
"html-loader": "0.5.5",
"html-webpack-plugin": "3.2.0",
"ignore-styles": "5.0.1",
"istanbul-instrumenter-loader": "3.0.1",
"jsdom": "14.0.0",
"jsdom-global": "3.0.2",
"mocha": "6.1.2",
"ng-annotate-loader": "0.6.1",
"node-sass": "4.11.0",
"rimraf": "2.6.2",
"sass-loader": "7.1.0",
"style-loader": "0.23.1",
"ts-node": "8.0.3",
"typescript": "3.4.2",
"uglifyjs-webpack-plugin": "2.0.1",
"webpack": "4.23.1",
"webpack-cli": "3.1.2",
"webpack-merge": "4.1.4"
},
"dependencies": {
"angular": "1.7.5",
"core-js": "3.0.1",
"growl": "1.10.5",
"jquery": "3.3.1",
"underscore": "1.9.1"
}
}
I cannot share the source code, but I used this angularjs webpack starter project to start mine.
Issues with invalid sourcemaps in Webpack and terser-webpack-plugin are addressed starting with webpack 4.39.2 and terser-webpack-plugin 1.4.0.
v4.39.0 release log:
webpack-sources + terser-webpack-plugin comes with quality optimizations for SourceMaps
There was an additional issue, whose fix was published later. It was included for webpack-sources v1.4.2/webpack 4.39.2. In conclusion 4.39.2or latest version is the one to go.
Details
Sourcemaps in production mode seem to work as expected in most cases now. Unfortunately, if you have non trivial code transformations like inlining of functions (that exist in source code, but are dissolved from webpack) in the course of uglyfying/minification/optimization, breakpoints sometimes still don't get mapped well. Part of the reason is, that the sourcemap spec is vague concerning those aspects.
I am trying to import "Cheerio.js" for web scraping purpose. When I try to run it. I am getting "Module Parse Failed Error: You may need an appropriate loader to handle this file type." It seems like I have to install extra loader or change my configuration in my webpack.config.js but I am having hard time trying to solve this issue. Could anyone please help me solve this issue?
Here is the error that I am getting:
ERROR in ./~/har-schema/lib/log.json
Module parse failed: /Users/taelee/Desktop/reactReduxBoilerPlate/ReduxSimpleStarter/node_modules/har-schema/lib/log.json Unexpected token (2:7)
You may need an appropriate loader to handle this file type.
Here is my webpack.config.js file:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1', 'stage-0']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
Here is my package.json file:
{
"name": "redux-simple-starter",
"version": "1.0.0",
"description": "Simple starter package for Redux with React and Babel support",
"main": "index.js",
"repository": "git#github.com:StephenGrider/ReduxSimpleStarter.git",
"scripts": {
"start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
"test:watch": "npm run test -- --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.2.1",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.1.18",
"chai": "^3.5.0",
"chai-jquery": "^2.0.0",
"jquery": "^2.2.1",
"jsdom": "^8.1.0",
"mocha": "^2.4.5",
"react-addons-test-utils": "^0.14.7",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
},
"dependencies": {
"axios": "^0.17.1",
"babel-preset-stage-1": "^6.1.18",
"cheerio": "^1.0.0-rc.2",
"jsonp": "^0.2.1",
"lodash": "^3.10.1",
"moment": "^2.19.2",
"prop-types": "^15.6.0",
"react": "^0.14.3",
"react-ace": "^5.10.0",
"react-ace-editor": "0.0.2",
"react-dom": "^0.14.3",
"react-redux": "4.3.0",
"react-router": "^2.0.1",
"react-router-redux": "^4.0.8",
"redux": "^3.0.4",
"redux-promise": "^0.5.3",
"request": "^2.85.0",
"request-promise": "^4.2.2"
}
}
Could anyone please help me solve this issue?
Thank you.
Try this out:
1) configuration.resolve.extensions[0] should not be empty
2) use loader: 'babel-loader', make sure you have babel-loader installed
module.exports = {
context: `${__dirname}/src`,
entry: [
'./index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}]
},
resolve: {
extensions: ['.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
I want to use the new ES2018 spread operator for objects, and I found that this NPM package should enable it: babel-plugin-transform-object-rest-spread
My package.json:
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"build": "node build/build.js"
},
"dependencies": {
"npm-sass": "^2.2.1",
"vue": "^2.5.13",
"vue-event-hub": "^1.0.2",
"vue2-datepicker": "^1.8.3"
},
"devDependencies": {
"#babel/plugin-proposal-optional-chaining": "^7.0.0-beta.40",
"autoprefixer": "^8.1.0",
"babel-core": "^6.26.0",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.3",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-plugin-transform-vue-jsx": "^3.5.1",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015-node6": "^0.4.0",
"babel-preset-stage-2": "^6.24.1",
"chalk": "^2.3.2",
"copy-webpack-plugin": "^4.5.0",
"css-loader": "^0.28.10",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.11",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^3.0.4",
"node-notifier": "^5.2.1",
"optimize-css-assets-webpack-plugin": "^4.0.0",
"ora": "^2.0.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.1.0",
"postcss-loader": "^2.1.1",
"postcss-url": "^7.3.1",
"rimraf": "^2.6.2",
"semver": "^5.5.0",
"shelljs": "^0.8.1",
"uglifyjs-webpack-plugin": "^1.2.2",
"url-loader": "^1.0.1",
"vue-loader": "^14.1.1",
"vue-style-loader": "^4.0.2",
"vue-template-compiler": "^2.5.13",
"webpack": "^4.1.0",
"webpack-bundle-analyzer": "^2.11.1",
"webpack-dev-server": "^3.1.0",
"webpack-merge": "^4.1.2"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
And of course in package-lock.json
"babel-plugin-transform-object-rest-spread": {
"version": "6.26.0",
"resolved": "https://registry.npmjs.org/babel-plugin-transform-object-rest-spread/-/babel-plugin-transform-object-rest-spread-6.26.0.tgz",
"integrity": "XXXXXXXXXXX",
"dev": true,
"requires": {
"babel-plugin-syntax-object-rest-spread": "6.13.0",
"babel-runtime": "6.26.0"
}
},
Here is the link to the NPM package: https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread
There isnt much to it, thats why its harder for me to figure out the cause.
I tried installing: babel-preset-es2015-node6, but that didnt help and I tried adding "es2015-node6" to the "presets" in .babelrc, also without any luck.
So now when I try using it, I get an error during the build process:
- invalid expression: Unexpected token ... in
{ ...selected_car, date: state.todays_date.toLocaleDateString()}
This error is cause by this:
<div>
<Car v-if="cars.length > 0" v-for="(car,index) in cars" :key="'car-'+index" :data="{ ...car, date: state.todays_date.toLocaleDateString()}" :selected="false" />
<Car v-if="selected_cars.length > 0" v-for="(selected_car,ind) in selected_cars" :key="'selected-car-'+ind" :data="{ ...selected_car, date: state.todays_date.toLocaleDateString()}" :selected="true"/>
</div>
In the :data attribute of the Car Vue component.
Sorry, I mistakenly delated my .babelrc in my last edit:
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["babel-plugin-transform-es2015-destructuring", "transform-object-rest-spread", "transform-vue-jsx", "transform-runtime"]
}
My webpack.base.conf.js looks like this:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('Images/[name].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('Stylesheets/[name].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
In order to use Object rest spread in templates, you need to:
Use Node v8.3+
Configure buble option for vue-loader:
buble: { objectAssign: 'Object.assign' }
If targeting any IE, make sure to include polyfill for Object.assign.
Please use following configuration in your build/vue-loader.conf.js file
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
transformToRequire: {
video: 'src',
source: 'src',
img: 'src',
image: 'xlink:href'
},
buble: { objectAssign: 'Object.assign' }
}
For more help please use check the same type of issue here.
I have created demo ESNext-In-vue repository for use Object rest spread in Vue templates.
Hopes this will help you !!