Fix and solution:
Thanks to #BoyWithSilver, long story short, here are what I did to fix my problems:
added .less into extensions section
removed unnecessary codes in webpack.config.json e.g. removed the extract-text-webpack-plugin
downgrade less from 3.0.1 to 2.7.0 fixed heaps of errors: length of undefined in index.less file in antd.
Update 3
Here is my package.json
{
"name": "mobx-reactjsx",
"version": "1.0.0",
"description": dfsdfsdfsd",
"scripts": {
"start": "webpack-dev-server --config webpack.config.js --progress --inline",
"lint": "eslint src"
},
"keywords": [
"react",
"reactjs",
"boilerplate",
"mobx",
"starter-kit",
"firebase",
"re-base"
],
"author": "Winston Fan",
"license": "MIT",
"homepage": "https://horizontalvision.azurewebsites.net/",
"devDependencies": {
"autoprefixer": "^8.0.0",
"babel-core": "^6.9.1",
"babel-loader": "^7.1.2",
"babel-plugin-import": "^1.6.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-1": "^6.5.0",
"css-loader": "^0.28.9",
"extract-text-webpack-plugin": "^3.0.2",
"less": "^3.0.1",
"less-loader": "^4.0.5",
"less-vars-to-js": "^1.2.1",
"postcss-loader": "^2.1.0",
"style-loader": "^0.20.2",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
},
"dependencies": {
"antd": "^3.2.1",
"firebase": "^4.9.1",
"mobx": "^3.5.1",
"mobx-react": "^4.4.1",
"mobx-react-devtools": "^4.2.15",
"re-base": "^3.2.2",
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
Update 2:
After removed the context option :
// context: path.resolve(__dirname, 'dist'),
in webpage.config.js
added
javascriptEnabled: true
under less-loader in webpack.config.json
I received these errors.
ERROR in ./node_modules/antd/lib/button/style/index.less Module build
failed:
/* stylelint-disable
declaration-bang-space-before,no-duplicate-selectors */ ^ Cannot read
property 'length' of undefined
in F:\temp\Playground\mobx-reactjsx\node_modules\antd\lib\style\color\bezierEasing.less
(line 1, column -1) # ./node_modules/antd/lib/button/style/index.js
5:0-23 # ./src/index.js # multi
(webpack)-dev-server/client?http://localhost:8080 ./src/index.js
ERROR in ./node_modules/antd/lib/style/index.less Module build failed:
/* stylelint-disable
declaration-bang-space-before,no-duplicate-selectors */ ^ Cannot read
property 'length' of undefined
in F:\temp\Playground\mobx-reactjsx\node_modules\antd\lib\style\color\bezierEasing.less
(line 1, column -1) # ./node_modules/antd/lib/button/style/index.js
3:0-33 # ./src/index.js # multi
(webpack)-dev-server/client?http://localhost:8080 ./src/index.js
ERROR in ./node_modules/antd/lib/style/index.less Module build failed:
ModuleBuildError: Module build failed:
/* stylelint-disable
declaration-bang-space-before,no-duplicate-selectors */ ^ Cannot read
property 'length' of undefined
in F:\temp\Playground\mobx-reactjsx\node_modules\antd\lib\style\color\bezierEasing.less
(line 1, column -1)
at runLoaders (F:\temp\Playground\mobx-reactjsx\node_modules\webpack\lib\NormalModule.js:195:19)
at F:\temp\Playground\mobx-reactjsx\node_modules\loader-runner\lib\LoaderRunner.js:364:11
at F:\temp\Playground\mobx-reactjsx\node_modules\loader-runner\lib\LoaderRunner.js:230:18
at context.callback (F:\temp\Playground\mobx-reactjsx\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
at
at process._tickCallback (internal/process/next_tick.js:169:7) # ./node_modules/antd/lib/style/index.less #
./node_modules/antd/lib/button/style/index.js # ./src/index.js #
multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
ERROR in ./node_modules/antd/lib/button/style/index.less Module build
failed: ModuleBuildError: Module build failed:
/* stylelint-disable
declaration-bang-space-before,no-duplicate-selectors */ ^ Cannot read
property 'length' of undefined
in F:\temp\Playground\mobx-reactjsx\node_modules\antd\lib\style\color\bezierEasing.less
(line 1, column -1)
at runLoaders (F:\temp\Playground\mobx-reactjsx\node_modules\webpack\lib\NormalModule.js:195:19)
at F:\temp\Playground\mobx-reactjsx\node_modules\loader-runner\lib\LoaderRunner.js:364:11
at F:\temp\Playground\mobx-reactjsx\node_modules\loader-runner\lib\LoaderRunner.js:230:18
at context.callback (F:\temp\Playground\mobx-reactjsx\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
at
at process._tickCallback (internal/process/next_tick.js:169:7) # ./node_modules/antd/lib/button/style/index.less #
./node_modules/antd/lib/button/style/index.js # ./src/index.js #
multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
Child extract-text-webpack-plugin
node_modules/extract-text-webpack-plugin/dist
node_modules/css-loader/index.js!node_modules/less-loader/dist/cjs.js??ref--1-2!node_modules/antd/lib/style/index.less:
[0] ./node_modules/css-loader!./node_modules/less-loader/dist/cjs.js?{"modifyVars":{"#primary-color":"#193D71"},"root":"F://temp//Playground//mobx-reactjsx","javascriptEnabled":true}!./node_modules/antd/lib/style/index.less
302 bytes {0} [built] [failed] [1 error]
ERROR in ./node_modules/css-loader!./node_modules/less-loader/dist/cjs.js?{"modifyVars":{"#primary-color":"#193D71"},"root":"F://temp//Playground//mobx-reactjsx","javascriptEnabled":true}!./node_modules/antd/lib/style/index.less
Module build failed:
/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors */
^
Cannot read property 'length' of undefined
in F:\temp\Playground\mobx-reactjsx\node_modules\antd\lib\style\color\bezierEasing.less
(line 1, column -1) Child extract-text-webpack-plugin
node_modules/extract-text-webpack-plugin/dist
node_modules/css-loader/index.js!node_modules/less-loader/dist/cjs.js??ref--1-2!node_modules/antd/lib/button/style/index.less:
[0] ./node_modules/css-loader!./node_modules/less-loader/dist/cjs.js?{"modifyVars":{"#primary-color":"#193D71"},"root":"F://temp//Playground//mobx-reactjsx","javascriptEnabled":true}!./node_modules/antd/lib/button/style/index.less
302 bytes {0} [built] [failed] [1 error]
ERROR in ./node_modules/css-loader!./node_modules/less-loader/dist/cjs.js?{"modifyVars":{"#primary-color":"#193D71"},"root":"F://temp//Playground//mobx-reactjsx","javascriptEnabled":true}!./node_modules/antd/lib/button/style/index.less
Module build failed:
/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors */
^
Cannot read property 'length' of undefined
in F:\temp\Playground\mobx-reactjsx\node_modules\antd\lib\style\color\bezierEasing.less
(line 1, column -1) webpack: Failed to compile.
Update 1:
Here is my webpack.config.json
var path = require('path');
var webpack = require('webpack');
const fs = require('fs');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const lessToJs = require('less-vars-to-js');
const themeVariables = lessToJs(fs.readFileSync(path.join(__dirname, './scripts/ant-theme-vars.less'), 'utf8'));
module.exports = {
watch: true,
context: path.resolve(__dirname, './src'),
devtool: 'source-map',
entry: [
'./src/index.js'
],
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ExtractTextPlugin('style.css')
],
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.jsx?$/,
use: ['babel-loader'],
include: path.join(__dirname, 'src')
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract([
{loader: "css-loader"},
{loader: "less-loader",
options: {
modifyVars: themeVariables,
root: path.resolve(__dirname, './')
}
}
])
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: "css-loader"
})
},]
}
};
now error message becomes:
ERROR in multi (webpack)-dev-server/client?http://localhost:8080
./src/index.js Module not found: Error: Can't resolve './src/index.js'
in '/Users/Winston/tmp/Playground/mobx-reactjsx/src' # multi
(webpack)-dev-server/client?http://localhost:8080 ./src/index.js
(project structure)
I do have index.js under projectfolder/src
I'm trying to integrate Ant Design with Less support and the Import on Demand feature which is here:
https://ant.design/docs/react/use-with-create-react-app
in Advanced Guide section.
In this section, it uses react-app-rewired but my project uses webpack 3(my project is based on this https://github.com/mobxjs/mobx-react-boilerplate), so cannot use the rewired command in my case.
So I found another article:
https://medium.com/#GeoffMiller/how-to-customize-ant-design-with-react-webpack-the-missing-guide-c6430f2db10f
Here is my code:
package.json
"start": "webpack-dev-server --hot --open",
webpack.config.json
const fs = require('fs');
const lessToJs = require('less-vars-to-js');
const themeVariables = lessToJs(fs.readFileSync(path.join(__dirname, './scripts/ant-theme-vars.less'), 'utf8'));
....
module:{
.....
rules:[
.....
test: /\.less$/,
use: [
{loader: "style-loader"},
{loader: "css-loader"},
{loader: "less-loader",
options: {
modifyVars: themeVariables
}
}
]
]
}
index.js
import {Button} from 'antd';
<Button type="primary">Hi!</Button>
.babelrc
{
"presets": [
"react",
"es2015",
"stage-1"
],
"plugins": [
["import", {"libraryName": "antd", "style": true} ],
"transform-decorators-legacy"
]
}
Here is the error messages from console:
For me i just had to use import 'antd/dist/antd.min.css
instead of import 'antd/dist/antd.css
https://github.com/ant-design/ant-design/issues/33327#issuecomment-997355323
The error seems to be coming from the inability to resolve .less files. Adding this to webpack.config.js should help resolve them:
resolve: {
extensions: ['.js', '.jsx', '.less']
},
You have specified context as src folder in the structure. This means the entry has to be changed to ./index.js or just ./index
If you did not mean to have context key, removing it will also do the work.
Webpack configuration (webpack.config.js):
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const fs = require('fs');
const lessToJs = require('less-vars-to-js');
const themeVariables = lessToJs(fs.readFileSync(path.join(__dirname, 'ant-theme-vars.less'), 'utf8'));
module.exports = {
watch: true,
context: path.resolve(__dirname, './src'),
entry: {
app: './index.js',
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].bundle.js',
},
devtool: 'source-map',
resolve: {
alias: {
moment: 'moment/src/moment'
},
},
module: {
rules: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['env','react','stage-2']
}
},
{
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.js$/,
options: {
presets: ['env','react','stage-2'],
plugins: [
['import', { libraryName: "antd", style: true }]
]
},
},
{
test: /\.scss?$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
loader: 'css-loader!sass-loader'
})
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract([
{loader: "css-loader"},
{loader: "less-loader",
options: {
modifyVars: themeVariables,
root: path.resolve(__dirname, './')
}
}
])
},
{
test: /\.(woff|woff2|eot|ttf|otf|svg|png|jpg,pdf)$/,
loader: "file-loader"
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
]
},
plugins: [
new ExtractTextPlugin('style.css')
],
devServer: {
port: 9000,
contentBase: 'dist'
}
};
And package.json:
{
"name": "ant-design-app",
"version": "1.0.0",
"description": "Ant design",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config webpack.config.js --progress --inline",
"build": "webpack -p --config webpack.config.js"
},
"repository": {
"type": "git",
"url": ""
},
"author": "Sivadass",
"license": "MIT",
"dependencies": {
"antd": "^3.1.4",
"moment": "^2.20.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-import": "^1.6.3",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.9",
"extract-text-webpack-plugin": "^2.1.2",
"file-loader": "^0.11.2",
"less": "^2.7.3",
"less-loader": "^4.0.5",
"less-vars-to-js": "^1.2.1",
"node-sass": "^4.7.2",
"postcss-loader": "^2.0.10",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"sugarss": "^1.0.1",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.1"
}
}
Ant theme variables configuration (ant-theme-vars.less):
#primary-color: #4099ff;
#font-size-base: 16px;
#font-family : "Proxima Nova", Helvetica Neue, Helvetica, Arial, sans-serif;
#btn-font-size-lg: 15px;
#btn-padding-lg : 8px 32px;
#btn-padding-sm : 4px 16px;
Solution for React :
in index.js folder
import 'antd/dist/antd.css
replace with
import 'antd/dist/antd.min.css
I just added that import statement into my index.scss file, then the warnings were disappeared
#import "antd/dist/antd.css";
Related
I'm getting crazy about the configuration of my React-Typescript-Webpack application. It is built from scratch - no create-react-app - and should work with the UI library "antd" and "storybook" as well.
After countless hours I now receive following error:
ERROR in ./node_modules/antd/lib/button/style/index.less 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
... which tells that webpack does not recognize the settings for less in webpack.config.js, right?
I just don't understand why, because I thought that I added everything necessary ... Can you please help and tell me what I'm doing wrong here?
Here is webpack.config.js:
const path = require("path");
const fs = require("fs");
const lessToJs = require("less-vars-to-js");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "none",
entry: {
app: path.join(__dirname, "src", "index.tsx"),
},
target: "web",
resolve: {
extensions: [".ts", ".tsx", ".js", ".less"],
},
module: {
rules: [
{
loader: "babel-loader",
exclude: /node_modules/,
test: /\.js$/,
options: {
plugins: [["import", { libraryName: "antd", style: true }]],
},
},
{
test: /\.less$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{loader: "less-loader"},
],
},
{
use: ["style-loader", "css-loader"],
test: /\.css$/,
},
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: "/node_modules/",
},
],
},
output: {
filename: "[name].js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "index.html"),
}),
],
};
And the babel.rc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
"#babel/proposal-class-properties",
"#babel/proposal-object-rest-spread",
"#babel/plugin-proposal-class-properties",
["import",
{
"libraryName": "antd",
"style": true // or 'css'
}]
]
}
And the dependencies from package.json:
"dependencies": {
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/plugin-proposal-object-rest-spread": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"antd": "^4.4.1",
"babel-plugin-import": "^1.13.0",
"css-loader": "^3.6.0",
"less": "2.7.2",
"less-vars-to-js": "^1.3.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"style-loader": "^1.2.1"
},
"devDependencies": {
"#babel/core": "^7.10.4",
"#storybook/addon-actions": "^5.3.19",
"#storybook/addon-links": "^5.3.19",
"#storybook/addons": "^5.3.19",
"#storybook/react": "^5.3.19",
"#types/antd": "latest",
"#types/react": "^16.8.24",
"#types/react-dom": "^16.0.5",
"#types/webpack": "4.1.4",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.3.0",
"less-loader": "^6.2.0",
"ts-loader": "^6.2.1",
"typescript": "^3.4.3",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.11.0"
}
For example, I use antd in App.tsx just like this:
import React, { FC } from 'react';
import { Button } from 'antd';
import './App.css';
import 'antd/dist/antd.css';
const App: FC = () => (
<div className="App">
<Button type="primary">Button</Button>
</div>
);
export default App;
When I run npm run build / npm start, everything works fine. The error appears when running npm run storybook as stated in the storybook docs.
Full error stack:
ERROR in ./node_modules/antd/lib/button/style/index.less 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> #import '../../style/themes/index';
| #import '../../style/mixins/index';
| #import './mixin';
# ./node_modules/antd/lib/button/style/index.js 5:0-23
# ./stories/2-Button.stories.js
# ./stories sync ^\.\/(?:(?:(?!\.)(?:(?:(?!(?:|[\\/])\.).)*?)[\\/])?(?!\.)(?=.)[^\\/]*?\.stories\.js[\\/]?)$
# ./.storybook/generated-entry.js
# multi ./node_modules/#storybook/core/dist/server/common/polyfills.js ./node_modules/#storybook/core/dist/server/preview/globals.js ./.storybook/generated-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=true
ERROR in ./node_modules/antd/lib/style/index.less 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> #import './themes/index';
| #import './core/index';
|
# ./node_modules/antd/lib/button/style/index.js 3:0-33
# ./stories/2-Button.stories.js
# ./stories sync ^\.\/(?:(?:(?!\.)(?:(?:(?!(?:|[\\/])\.).)*?)[\\/])?(?!\.)(?=.)[^\\/]*?\.stories\.js[\\/]?)$
# ./.storybook/generated-entry.js
# multi ./node_modules/#storybook/core/dist/server/common/polyfills.js ./node_modules/#storybook/core/dist/server/preview/globals.js ./.storybook/generated-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=true
Help will be much appreciated!
Please notice you have two rules for .less,
One executes after the other completes.
Try taking one of them off please.
I had the same problem and here are the steps I did to resolve;
My package.json,
"css-loader": "^3.5.3",
"less": "^3.12.2",
"less-loader": "^7.0.0",
"style-loader": "^1.2.0",
"url-loader": "^4.1.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
My webpack rules config,
{
test: /\.less$/,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
lessOptions: {
javascriptEnabled: true,
},
},
},
],
},
Note: Before less 3.11, the javascriptEnabled is directly inside options
I'm new to React, webpack, Babel.... all of it. Trying to setup a vanilla project where I want to utilize Salesforce Lightning Design System for React. npm run start shows the following error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: [BABEL] /Users/brandor/test/react_tut/src/index.js: Cannot find module 'babel-preset-env'
Require stack:
- /Users/brandor/test/react_tut/node_modules/#salesforce/babel-preset-design-system-react/index.js
I'm not sure why it's stating that 'babel-preset-env' is required. Shouldn't that have been installed when I installed the slds modules with the following?
$ npm install #salesforce-ux/design-system #salesforce/design-system-react
If I do install the module (along with one other it complains about) then I get something that seems to be related to this issue, but I'm using what looks like the correct presets in my babel.config.js file.
The other error is:
TypeError: /Users/brandor/test/react_tut/src/components/App.js: Cannot read property 'bindings' of null which
Not sure if this is an issue with webpack config, babel, or incorrect version of something.
package.json
{
"name": "react_tut",
"version": "1.0.0",
"description": "Boilerplate stuff",
"main": "index.js",
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open --hot"
},
"license": "MIT",
"dependencies": {
"#salesforce-ux/design-system": "^2.11.6",
"#salesforce/design-system-react": "^0.10.18",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-export-extensions": "^6.22.0",
"core-js": "^3.6.4",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/preset-flow": "^7.8.3",
"#babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"url-loader": "^4.0.0",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
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',
resolve: {
modules: ['src', 'node_modules'],
extensions: ['.js', '.jsx']
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.join(__dirname, 'src/js'),
path.join(__dirname, 'node_modules/#salesforce/design-system-react'),
],
exclude: [
path.join(
__dirname,
'node_modules/#salesforce/design-system-react/node_modules',
),
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.(svg|gif|jpe?g|png)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|woff|woff2|ttf)$/,
loader: 'url-loader?limit=30&name=assets/fonts/webfonts/[name].[ext]'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
}),
],
};
babel.config.js
'use strict';
const presets = ['#babel/preset-react', '#babel/preset-flow', '#salesforce/babel-preset-design-system-react'];
module.exports = {
presets: [
...presets,
[
'#babel/preset-env',
{
modules: false,
corejs: '3',
useBuiltIns: 'usage',
},
],
],
env: {
test: {
presets: [
...presets,
[
'#babel/preset-env',
{
targets: { node: 'current' },
corejs: '3',
useBuiltIns: 'usage',
},
],
],
},
},
};
Im tring to compile my react frontend app but I got a couple of error about "..." syntax:
ERROR in condition.jsx
Module build failed: SyntaxError: Unexpected token (25:10)
23 | show_table : undefined,
24 | fa_count : 0,
> 25 | ...this.state
| ^
26 | }
condition.jsx extends (with OOP) another component so I need ...this.state to merge parent state with the local state.
When launcing it with npm start, it works perfectly but the compiler seems doesn't want that syntax.
UPDATED:
This is my current webpack settings:
const webpack = require('webpack');
const path = require('path');
const Uglify = require("uglifyjs-webpack-plugin");
var plugins = [];
plugins.push(new Uglify());
var config = {
context: __dirname + '/src',
entry: {
javascript: "./index.js",
},
plugins: plugins,
output: {
path: path.join(__dirname,'../static/js/'),
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test:/\.(js|jsx)?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env','react']
}
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
]
},
}
module.exports = env => {
return config;
}
Lanching with this command:
./node_modules/.bin/webpack --config webpack.config.js
In a comment, you said that you don't have any babelrc. Then I already re-read the Webpack offical document and take this sample code from there for you:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
}
}
]
after installing the babel-plugin-transform-object-rest-spread package, you could follow this sample code to update your webpack config. Read more about it: Webpack Loader
This is the combination that works for me, I'm using the babel-preset-stage-2 instead.
In the webpack.config.js:
....
module: {
rules: [
{
test:/\.(js|jsx)?$/,
use: ['babel-loader']
},
....
]
}
....
I create a .babelrc file in the root folder and its content is:
{
"presets": ["env", "react", "stage-2"],
....
}
And this is my package.json file:
{
"name": "demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.9.0",
"react-hot-loader": "^4.3.3",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"webpack": "^4.15.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"uuid": "^3.3.2"
}
}
Hopefully, it works for you.
You didn't tell about your configuration. But I assume babel and webpack. This seems to be an issue with your babel config. Try this plugin:
https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread
After you've installed it, add
"plugins": ["transform-object-rest-spread"]
To your .babelrc file and run the webpack again.
I am trying to implement this to see how it works but i cannot get it to build
https://ashiknesin.com/blog/build-custom-sidebar-component-react/
In my webpack.config.js I have the following
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
const ExtractTextPlugin = require("extract-text-webpack-plugin");
/*const extractSass = new ExtractTextPlugin({
filename: "[name].[contenthash].css",
disable: process.env.NODE_ENV === "development"
});
*/
module.exports = {
entry : __dirname + '/app/index.js',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
],
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
output: {
filename: 'transformed.js',
path: __dirname + '/dist'
},
plugins: [
HTMLWebpackPluginConfig,
new ExtractTextPlugin("styles.css")
]
}
When I try to build it errors with
ERROR in ./app/index.js
Module parse failed: Unexpected token (20:12)
You may need an appropriate loader to handle this file type.
| render() {
| return (
| <div>
| <SideBar />
| <Header />
Child html-webpack-plugin for "index.html":
1 asset
[0] ./node_modules/html-webpack-plugin/lib/loader.js!./app/index.html 6.41 kB {0} [built]
[2] (webpack)/buildin/global.js 509 bytes {0} [built]
[3] (webpack)/buildin/module.js 517 bytes {0} [built]
+ 1 hidden module
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! ccp-react#1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the ccp-react#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /opt/SP/wwwadm/home/.npm/_logs/2017-12-29T11_17_11_139Z-debug.log
I have tried looking at the following posts but they don't seem to work. https://github.com/webpack-contrib/extract-text-webpack-plugin
https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/580
here is my webpack file
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry : __dirname + '/app/index.js',
module: {
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
}]
}],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'transformed.js',
path: __dirname + '/dist'
},
plugins: [
HTMLWebpackPluginConfig
]
}
here is my package file
{
"name": "ccp-react",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server",
"build": "webpack"
},
"private": true,
"dependencies": {
"babel-plugin-lodash": "^3.3.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"bootstrap": "^3.3.7",
"classnames": "^2.2.5",
"core-js": "^2.5.3",
"create-react-class": "^15.6.2",
"cross-env": "^5.1.3",
"gulp": "^3.9.1",
"hammerjs": "^2.0.8",
"lodash": "^4.17.4",
"ng": "0.0.0-rc6",
"ng-cli": "^0.7.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-sidenav": "^2.1.2",
"rxjs": "^5.5.6",
"semantic": "0.0.1",
"semantic-ui": "^2.2.13",
"semantic-ui-react": "^0.77.1",
"systemjs": "^0.20.19",
"web-animations-js": "^2.3.1",
"zone.js": "^0.8.19"
},
"devDependencies": {
"#types/jasmine": "~2.5.53",
"#types/jasminewd2": "~2.0.2",
"#types/node": "^6.0.95",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^2.30.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.3.3",
"karma-jasmine": "^1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"node-sass": "^4.7.2",
"protractor": "~5.1.2",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.1",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "~2.4.2",
"webpack": "^3.10.0",
"webpack-bundle-analyzer": "^2.8.2",
"webpack-dev-server": "^2.9.7"
}
}
Here is my index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Sidebar from './components/sidebar';
import Header from './components/header';
import HomeContent from './components/home';
class App extends Component {
constructor(props){
super(props);
this.state = { nav: '/' };
}
render() {
return (
<div>
<Header />
<Sidebar />
<HomeContent />
</div>
);
}
};
ReactDOM.render(<App/>, document.getElementById("app"));
my folder structure is
app/index.js
app/index.html
app/components/sidebar.js
app/components/home.js
app/components/header.js
dist/
docs/
package.json
webpack.config.js
.babelrc
node_modules
sidebar.js contains https://ashiknesin.com/blog/build-custom-sidebar-component-react/ , If I comment out the import css and remove the css loaders from webpack it builds fine.
If you are using Sass in your project, you need to tell webpack how to handle scss files, so you need to install sass-loader and include it in your webpack configuration. The very minimum is this:
module: {
rules: [{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
}]
},
Installation guide and other examples of webpack configurations with sass-loader are provided on sass-loader github homepage.
In order to install sass-loader, run npm install sass-loader node-sass --save-dev, more info here.
Here is the edited version of your webpack config (removed loaders since they are not supported in webpack 3 and replaced with a rule for for handling js files with babel-loader):
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry : __dirname + '/app/index.js',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
}]
}]
},
output: {
filename: 'transformed.js',
path: __dirname + '/dist'
},
plugins: [
HTMLWebpackPluginConfig
]
}
I am using webpack and trying to leverage an existing React component library written in TS.
However, with the settings below, the webpack is giving 'unexpected Token' error. I copied the problematic code to babel online transpiler https://babeljs.io/repl/ but it is not showing any error.
I am very new to React development, any criticism/questions/answers are welcomed.
Thanks!
This is my webpack.config.js
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/static/js/index'
],
output: {
path: path.resolve('./app/static/bundles/'),
filename: '[name]-[hash].js',
publicPath: 'http://localhost:3000/static/bundles/',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader?presets[]=es2015,presets[]=react"],
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
configFileName: './tsconfig.json'
},
exclude: /node_modules/
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.css']
}
}
My entry point file index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import * as PropTypes from 'prop-types';
interface IDemoState {
value ?: string;
}
class Test extends React.Component<{}, IDemoState> {
state: IDemoState = {
value : 'general'
}
}
ReactDOM.render(<Test />, document.getElementById('tabnav'));
Package.json
{
"name": "djangoproject",
"version": "1.0.0",
"description": "Django Project",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js --progress --colors",
"build-production": "webpack --config webpack.prod.config.js --progress --colors",
"watch": "node server.js"
},
"keywords": [
"Django"
],
"license": "ISC",
"devDependencies": {
"adp-css-framework": "^1.5.3",
"adp-react-components": "^1.4.3",
"adp-react-icons": "^1.16.0",
"babel": "^6.23.0",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.0",
"babel-preset-env": "^1.5.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-hot-loader": "^1.3.1",
"style-loader": "^0.18.2",
"ts-loader": "^2.2.1",
"typescript": "^2.4.1",
"webpack": "^3.0.0",
"webpack-bundle-tracker": "^0.2.0",
"webpack-dev-server": "^2.5.0"
}
}
If I run npm run watch, I got this error:
ERROR in ./app/static/js/index.js
Module build failed: SyntaxError: xxxxx./app/static/js/index.js: Unexpected token (10:20)
8 |
9 | class Test extends React.Component<{}, IDemoState> {
> 10 | state: IDemoState = {
| ^
11 | value : 'general'
12 | }
13 | }
# multi webpack-dev-server/client?http://localhost:3000 webpack/hot/only-dev-se
rver ./app/static/js/index
The problem finally goes away after I changed the ts-loader to awesome-typescript-loader and write everything in a tsx file.