I am building a number of web apps using reactjs, webpack, babel and yarn. I want to share some of my js(x) code between projects. Therefore I have have put it in a separate folder that i want to refer to from my projects (by using an alias in webpack.config.js).
It seems like babel-loader doesn't understand the reactjs syntax in the code I have in folder outside of my project root.
There is probably something wrong with my config somewhere, but I can't seem to find it. Is there anyone else that can?
Here is my webpack.config.js:
const webpack = require('webpack');
const path = require('path');
module.exports = env => {
return {
devtool: 'eval',
mode: 'development',
entry: ['index.jsx'],
output: {
filename: 'app.js',
publicPath: 'dist',
path: path.resolve('dist'),
},
// configure the dev server to run
devServer: {
port: 3001,
historyApiFallback: {
disableDotRule: true
},
inline: true,
},
resolve: {
extensions: ['.jsx', '.js'],
modules: ['src', 'node_modules'],
alias: {
$fff: path.resolve('/code/fff/src/')
}
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname),
path.resolve('/code/fff/src/')
],
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
mimtype: "text/css",
includePaths: []
}
}]
},
{
test: /\.css$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
mimtype: "text/css",
includePaths: []
}
}]
},
{
test: /\.(svg|png|ico|xml|json)$/,
loaders: ['file-loader'],
include: path.resolve('assets')
},
],
},
plugins: [
new webpack.DefinePlugin({
__API_URL: JSON.stringify(env.development ? 'https://localhost:44341/api/' : 'xxx/api/'),
__APPLICATION_KEY: JSON.stringify('CrossCheck')
})
]
};
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
package.json
{
"name": "CrossCheckFront",
"version": "1.0.0",
"main": "index.js",
"author": "4E2",
"license": "MIT",
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"bootstrap": "^4.4.1",
"cross-fetch": "^3.0.4",
"css-loader": "^3.4.2",
"eslint": "^6.8.0",
"file-loader": "^5.1.0",
"node-sass": "^4.13.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^7.2.0",
"react-redux-oauth2": "^0.5.14",
"react-router-dom": "^5.1.2",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3"
},
"scripts": {
"start": "webpack-dev-server --env.development",
"build": "webpack --env.production"
}
}
and here is part of the error output:
ERROR in C:/code/fff/src/InitResetPasswordPage/InitResetPasswordPage.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\code\fff\src\InitResetPasswordPage\InitResetPasswordPage.jsx: Unexpected token (47:12)
45 | return (
46 |
> 47 | <div className="h-100 row align-items-center">
| ^
48 | <div className="col lg-4"></div>
49 | <div className="col lg-4 fet-loginform">
50 | <h2 className="fet-header">Lösenordsåterställning</h2>
at Parser.raise (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:7044:17)
at Parser.unexpected (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:8422:16)
at Parser.parseExprAtom (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9701:20)
at Parser.parseExprSubscripts (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9287:23)
at Parser.parseMaybeUnary (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9267:21)
at Parser.parseExprOps (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9137:23)
at Parser.parseMaybeConditional (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9110:23)
at Parser.parseMaybeAssign (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9065:21)
at Parser.parseParenAndDistinguishExpression (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9842:28)
at Parser.parseExprAtom (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9622:21)
at Parser.parseExprSubscripts (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9287:23)
at Parser.parseMaybeUnary (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9267:21)
at Parser.parseExprOps (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9137:23)
at Parser.parseMaybeConditional (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9110:23)
at Parser.parseMaybeAssign (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9065:21)
at Parser.parseExpression (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:9017:23)
at Parser.parseReturnStatement (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11091:28)
at Parser.parseStatementContent (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:10772:21)
at Parser.parseStatement (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:10724:17)
at Parser.parseBlockOrModuleBlockBody (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11298:25)
at Parser.parseBlockBody (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11285:10)
at Parser.parseBlock (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11269:10)
at Parser.parseFunctionBody (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:10285:24)
at Parser.parseFunctionBodyAndFinish (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:10254:10)
at Parser.parseMethod (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:10216:10)
at Parser.pushClassMethod (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11704:30)
at Parser.parseClassMemberWithIsStatic (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11621:12)
at Parser.parseClassMember (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11563:10)
at C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:11518:14
at Parser.withTopicForbiddingContext (C:\code\CrossCheck\CrossCheckFront\node_modules\#babel\parser\lib\index.js:10599:14)
# C:/code/fff/src/InitResetPasswordPage/index.js 1:0-40 1:0-40
# ./src/App/App.jsx
# ./src/App/index.js
# ./src/index.jsx
# multi index.jsx
Related
I am setting up my ReactApp and just finished with it. So I wanted to make a settings class in a appsettings.ts file. So I can change some global variables easier.
But then all my issues started.
I know this problem is very common and there are tons of answers available but none of them have worked for me so far. I have searched through the internet to solve it but it still shows the same error.
This is the error I am getting:
ERROR in ../../../appsettings.ts
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: [APP_DIR]\appsettings.ts: Unexpected token (2:11)
1 | export class APPSETTINGS {
> 2 | public static EMAIL_SENDER: string = "name#example.com";
| ^
3 | public static EMAIL_RECIPIENT: string = "name#example.com";
4 | public static YEAR: number = (new Date()).getFullYear();
5 | }
at instantiate ([APP_DIR]\node_modules\#babel\parser\lib\index.js:67:32)
at constructor ([APP_DIR]\node_modules\#babel\parser\lib\index.js:364:12)
at Parser.raise ([APP_DIR]\node_modules\#babel\parser\lib\index.js:3364:19)
at Parser.unexpected ([APP_DIR]\node_modules\#babel\parser\lib\index.js:3397:16)
at Parser.parseClassMemberWithIsStatic ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13888:12)
at Parser.parseClassMember ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13773:10)
at [APP_DIR]\node_modules\#babel\parser\lib\index.js:13715:14
at Parser.withSmartMixTopicForbiddingContext ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12617:14)
at Parser.parseClassBody ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13694:10)
at Parser.parseClass ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13669:22)
at Parser.parseExportDeclaration ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14178:25)
at Parser.maybeParseExportDeclaration ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14135:31)
at Parser.parseExport ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14058:29)
at Parser.parseStatementContent ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13020:27)
at Parser.parseStatement ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12917:17)
at Parser.parseBlockOrModuleBlockBody ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13497:25)
at Parser.parseBlockBody ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13489:10)
at Parser.parseProgram ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12832:10)
at Parser.parseTopLevel ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12822:25)
at Parser.parse ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14674:10)
at parse ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14716:38)
at parser ([APP_DIR]\node_modules\#babel\core\lib\parser\index.js:41:34)
at parser.next (<anonymous>)
at normalizeFile ([APP_DIR]\node_modules\#babel\core\lib\transformation\normalize-file.js:66:38)
at normalizeFile.next (<anonymous>)
at run ([APP_DIR]\node_modules\#babel\core\lib\transformation\index.js:21:50)
at run.next (<anonymous>)
at transform ([APP_DIR]\node_modules\#babel\core\lib\transform.js:22:41)
at transform.next (<anonymous>)
at step ([APP_DIR]\node_modules\gensync\index.js:261:32)
at [APP_DIR]\node_modules\gensync\index.js:273:13
at async.call.result.err.err ([APP_DIR]\node_modules\gensync\index.js:223:11)
# ./src/Page/Main/index.tsx 24:0-60 204:60-76 298:42-58
# ./src/App.tsx 5:0-31 14:38-42
# ./src/index.tsx 3:0-24 4:50-53
webpack 5.75.0 compiled with 1 error in 4752 ms
I got this error after I imported APPSETTINGS into my react app. If I delete the usage, then everything compiles fine, but with it, it just gives me this error
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotenv = require('dotenv');
const CopyPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv.development === true;
const isEnvProduction = webpackEnv.production === true;
return {
target: 'web',
watch: isEnvDevelopment,
mode: isEnvProduction ? 'production' : 'development',
entry: "./src/index.tsx",
output: {
path: path.join(__dirname, 'dist'),
publicPath: "/",
filename: isEnvProduction ? '[id].[hash].js' : '[name].bundle.js',
chunkFilename: isEnvProduction ? '[id].[hash].[chunkhash].chunk.js' : '[name].chunk.js',
},
devtool: isEnvDevelopment ? "source-map" : false,
devServer: {
compress: true,
port: 9000,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization",
https: true
},
historyApiFallback: true
},
resolve: {
mainFields: ['browser', 'main', 'module'],
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
// we use babel-loader to load our jsx and tsx files
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-env"
]
}
},
},
{
test: /\.(css|scss)$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: {
localIdentName: isEnvProduction ? '[sha512:contenthash:base64]' : '[sha1:contenthash:hex:5]_____[local]'
},
importLoaders: 2,
sourceMap: isEnvDevelopment,
}
},
{
loader: "resolve-url-loader",
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
},
{
test: /\.(eot|otf|webp|ttf|woff|woff2|jpe?g|png|gif|svg)$/,
type: 'asset/resource'
},
{
test: /\.(pdf)(\?.*)?$/,
use: [
{
loader: "file-loader",
options: {
outputPath: "binary",
publicPath: "/binary"
}
},
],
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: isEnvProduction ? '[id].[hash].css' : '[name].bundle.css',
}),
new HtmlWebpackPlugin(),
new CopyPlugin({
patterns: [
{ from: 'src/static', to: '.' },
],
}),
new Dotenv({
path: isEnvProduction ? path.join(__dirname, "./.env.automated") : path.join(__dirname, "./.env")
}),
]
}
};
package.json
{
"name": "react-webapp",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"scripts": {
"dev": "webpack serve --env development",
"build": "webpack --env production"
},
"author": "",
"license": "ISC",
"dependencies": {
"#aws-amplify/api": "^4.0.18",
"#aws-amplify/api-graphql": "^2.2.7",
"#aws-amplify/auth": "^4.3.8",
"#aws-amplify/cache": "^4.0.20",
"#aws-amplify/core": "^4.3.0",
"aws-amplify": "^4.3.0",
"classnames": "^2.3.1",
"detect-browser": "^5.2.1",
"dotenv-webpack": "^7.0.3",
"graphql-tag": "^2.12.5",
"ibantools": "^4.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-loading": "^2.0.3",
"react-router-dom": "^5.3.0",
"regenerator-runtime": "^0.13.9"
},
"devDependencies": {
"#babel/core": "^7.20.2",
"#babel/plugin-proposal-class-properties": "^7.14.5",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.14.5",
"#babel/preset-typescript": "^7.15.0",
"#types/react": "^17.0.26",
"#types/react-dom": "^17.0.9",
"babel-loader": "^8.3.0",
"copy-webpack-plugin": "^9.0.1",
"css-loader": "^6.3.0",
"dotenv": "^10.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.3.0",
"node-sass": "^6.0.1",
"resolve-url-loader": "^4.0.0",
"sass-loader": "^12.1.0",
"typescript": "^4.4.3",
"typescript-plugin-css-modules": "^3.4.0",
"webpack": "^5.75.0",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.3.0"
}
}
You've installed #babel/preset-typescript but it's not added to the loader presets.
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-typescript"
"#babel/preset-env",
]
}
},
},
You may need to tweak the settings.
I am setting up mocha + chai + enzyme to test my react components.
I have set up the webpack.config.js file as below
webpack.config.js
const path = require("path");
const HtmlPlugin = require("html-webpack-plugin");
module.exports = {
node: {
fs: 'empty'
},
entry: "./App.js",
output: {
path: path.join(
__dirname, '/prod'
),
filename: "app.bundle.js",
},
module: {
rules: [
{
test: /\.js$|jsx/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
}
},
{ test: /\.js$|jsx/, use: 'mocha-loader' },
],
options: {
presets: ["es2015"]
},
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
plugins: [
new HtmlPlugin({
template: './public/index.html'
})
]
}
webpack.config.test.js
const webPackExternals = require('webpack-node-externals')
module.exports = {
mode:'development',
target: 'node',
externals: [webPackExternals()],
module: {
rules: [
{
test: /\*.test\.js$/,
use: ['mocha-loader'],
exclude: /node_modules/,
},
{ test: /\.css$/, use: 'css-loader' },
]
},
}
package.json
{
"name": "tobacco-free",
"version": "1.0.0",
"description": "",
"main": "App.js",
"scripts": {
"build": "webpack --mode production",
"dev": "webpack-dev-server --mode development --open --hot",
"start": "serve ./prod",
"test": "mocha-webpack --webpack-config webpack.config.test.js \"./src/**/*.test.js\"",
"coverage": "nyc --reporter=lcov --reporter=text npm run test"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"istanbul-instrumenter-loader": "^3.0.1",
"mapbox-gl": "^1.8.1",
"nyc": "^15.0.0",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"react-router-dom": "^5.1.2",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"serve": "^11.3.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "7",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"chai": "^4.2.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"html-webpack-plugin": "^3.2.0",
"mocha": "^7.1.1",
"mocha-loader": "^4.0.2",
"mocha-webpack": "2.0.0-beta.0",
"webpack-dev-server": "^3.10.3",
"webpack-node-externals": "^1.7.2"
}
}
When I run yarn test, I get this error
https://github.com/amkayondo/imgBank/blob/master/Annotation%202020-03-21%20173230.jpg
You may need an appropriate loader to hand
le this file type, currently no loaders are
configured to process this file.
But I don't know the loader it needs because I added the use: ['mocha-loader'] In thewebpack.config.js. Please help me with this bug
I replaced the mocha-loader with babel-loader to enable mocha to understand the .jsx files
I also replace the test: /\*.test.js$\/ with test: /\.js$|jsx/ to enable mocha to get access to the test and its component
I also add the resolve key to resolve: { extensions: ['*', '.js', '.jsx'],} in the webpack.config.test.js file to enable mocha to read js and jsx files
modified webpack.config.test.js
const webPackExternals = require('webpack-node-externals')
module.exports = {
mode:'development',
target: 'node',
externals: [webPackExternals()],
module: {
rules: [
{
test: /\.js$|jsx/,
use: 'babel-loader',
exclude: /node_modules/,
},
{ test: /\.css$/, use: 'css-loader' },
]
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
}
I've created webpack config to my VueJS project. I want to separate styles from javascript code. I've used mini-css-extract-plugin but finally I receive only bundle.js file. What's wrong with this config and where is a mistake? Is there any missing loader. My config is below:
import path from 'path';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import VueLoaderPlugin from 'vue-loader/lib/plugin';
import UglifyJsPlugin from 'uglifyjs-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
const devMode = process.env.NODE_ENV !== 'production';
const prodPlugins = [
new UglifyJsPlugin(),
new MiniCssExtractPlugin({
filename: "css/style.css"
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.optimize\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true
})
];
const basicPlugins = [
new CleanWebpackPlugin('dist'),
new VueLoaderPlugin()
];
const config = {
entry: {
bundle: './src/main.js'
},
output: {
filename: 'js/[name].js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
{
test: /\.css$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader'
]
},
{ test: /\.(scss|sass)$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
js: 'babel-loader',
}
}
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
plugins: !process.env.NODE_ENV || !devMode ? basicPlugins : basicPlugins.concat(prodPlugins)
};
module.exports = config;
My file package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --watch --mode development --hot",
"dev": "webpack-dev-server --mode development --progress --hot --open",
"build": "webpack --mode production --progress"
},
"author": "",
"license": "MIT",
"devDependencies": {
"autoprefixer-loader": "^3.2.0",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-register": "^6.26.0",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"cssnano": "^3.10.0",
"eslint": "^4.19.1",
"eslint-watch": "^3.1.4",
"mini-css-extract-plugin": "^0.4.0",
"node-sass": "^4.9.0",
"optimize-css-assets-webpack-plugin": "^4.0.1",
"sass-loader": "^7.0.1",
"sass-resources-loader": "^1.3.3",
"style-loader": "^0.21.0",
"uglifyjs-webpack-plugin": "^1.2.5",
"vue-loader": "^15.0.10",
"vue-style-loader": "^4.1.0",
"vue-template-compiler": "^2.5.16",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"axios": "^0.18.0",
"material-design-icons": "^3.0.1",
"vue": "^2.5.16",
"vue-router": "^3.0.1",
"vuetify": "^1.0.17"
}
}
Note that any imported file is subject to tree shaking. This means if you use something like css-loader in your project and import a CSS file, it needs to be added to the side effect list so it will not be unintentionally dropped in production mode.
Blockquote
in your package.json, add:
"sideEffects": [
'.scss'
]
In Webpack 4, you can add "sideEffects: true" to the loader to prevent the compiler from dropping the CSS file output by MiniCssExtractPlugin.loader (See Webpack Tree Shaking Guide). This works with Angular + TypeScript (using "module:" "ES2015" in tsconfig). I imagine it would work for your set up as well.
{
test: /\.scss$/,
include: [
helpers.root('src', 'assets')
],
sideEffects: true,
use: [
MiniCssExtractPlugin.loader,
{loader: 'css-loader'},
{loader: 'resolve-url-loader'}, // Angular only
{loader: 'sass-loader'},
]
},
Check that you have set the NODE_ENV environment variable.
In your config the extracting of css to separate files (MiniCssExtractPlugin) will only occur when building for production, in other words, when NODE_ENV is set to 'production'. When building for development style-loader is being used which will inject the css within a tag.
My setup is below. If I run gulp in the directory with these files, then I get a boatload of errors that look like the following. They all have a similar signature but are failing to find a different part of react-bootstrap, react-dom, or the like.
Module not found: Error: Can't resolve 'react-bootstrap/lib/Input' in '...a/scripts/components'
# ./a/scripts/components/SearchBar.js 7:12-48
# ./a/scripts/pages/HomePage.js
# ./a/scripts/routes.js
# ./a/scripts/index.js
# multi webpack-dev-server/client?http://localhost:8083 webpack/hot/only-dev-server ./a/scripts/index
This makes me think it's to do with the loader. And in fact, if I run npm install, then after verifying that everything is installed and making a bundle.js, this error occurs:
ERROR in ./a/scripts/index.js
Module parse failed: Unexpected token (19:15)
You may need an appropriate loader to handle this file type.
|
| Router.run(routes, Router.HistoryLocation, function(Handler) {
| React.render(<Handler />, document.getElementById('entry'));
| });
|
# multi ./a/scripts/index
Which also suggests it's with the loader. I've since spent a lot of time trying to figure out why the loader wouldn't be working and am coming up blank. Help would be greatly appreciated.
package.json
{
"version": "1.0.0",
"main": "index.js",
"engines": {
"node": "0.12.7",
"npm": "2.7.5"
},
"scripts": {
"postinstall": "gulp build"
},
"author": "",
"license": "none",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"css-loader": "^0.28.8",
"del": "^3.0.0",
"file-loader": "^1.1.6",
"gulp": "^3.9.1",
"gulp-autoprefixer": "^4.1.0",
"gulp-cache": "^1.0.2",
"gulp-clean-css": "^3.9.2",
"gulp-concat": "^2.5.2",
"gulp-imagemin": "^4.1.0",
"gulp-jshint": "^2.1.0",
"gulp-livereload": "^3.8.0",
"gulp-notify": "^3.1.0",
"gulp-rename": "^1.2.0",
"gulp-ruby-sass": "^3.0.0",
"gulp-uglify": "^3.0.0",
"jsx": "^0.9.89",
"jsx-loader": "^0.13.2",
"lodash": "^4.17.4",
"moment": "^2.9.0",
"node-sass": "^4.7.2",
"plugin-error": "^0.1.2",
"react": "^16.2.0",
"react-bootstrap": "^0.32.0",
"react-hot-loader": "^3.1.3",
"react-router": "^4.2.0",
"react-script-loader": "^0.0.1",
"run-sequence": "^2.2.1",
"sass-loader": "^6.0.6",
"sass-material-colors": "0.0.5",
"style-loader": "^0.19.1",
"superagent": "^3.8.2",
"underscore": "^1.8.3",
"url-loader": "^0.6.2",
"webpack": "^3.10.0",
"webpack-dev-server": "2.10.1"
},
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1"
},
}
.babelrc
{
"presets": ["env", "react"]
}
gulpfile.babel.js
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
cleanCSS = require('gulp-clean-css'),
rename = require('gulp-rename');
var log = require('fancy-log');
var PluginError = require('plugin-error');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require("./webpack.config.js");
var runSequence = require('run-sequence');
var path = require('path');
var del = require('del');
var watch = true;
var verbose = true;
// Default to Dev Server
gulp.task('default', ["js-dev-server"]);
// Clean output directory
gulp.task('clean', () => del(['a/static/js/build/*', 'a/static/css/*'], {dot:true}))
gulp.task('styles', function() {
return sass('a/static/scss/styles.scss', { style: 'expanded' })
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
.pipe(gulp.dest('a/static/css'))
.pipe(rename({suffix: '.min'}))
.pipe(cleanCSS())
.pipe(gulp.dest('a/static/css'));
});
gulp.task('watch', function() {
gulp.watch('a/static/scss/**/*.scss', ['styles']);
});
gulp.task('bundle', function() {
function bundle(err, stats) {
if (err) {
throw new PluginError("build", err);
}
console.log(stats.toString({
colors: true,
hash: verbose,
version: verbose,
timings: verbose,
chunks: verbose,
chunkModules: verbose,
cached: verbose,
cachedAssets: verbose
}));
}
webpack(webpackConfig).run(bundle)
});
gulp.task('build', ['clean'], cb => { runSequence(['styles', 'bundle']); });
gulp.task("js-dev-server", function(callback){
// modify some webpack config options
var myConfig = Object.create(webpackConfig);
myConfig.devtool = "eval-source-map";
myConfig.entry = [
'webpack-dev-server/client?http://localhost:8083',
'webpack/hot/only-dev-server',
'./a/scripts/index'
];
myConfig.plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.LoaderOptionsPlugin({debug: true})
];
myConfig.output['publicPath'] = "http://localhost:8083/static/js/build/"
myConfig.module = {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot-loader/webpack', 'jsx-loader?harmony', 'babel-loader']
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=image/svg+xml" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]=" +
path.resolve(__dirname, "./a/static/scss/")
}
]
};
// Start a webpack-dev-server
new WebpackDevServer(webpack(myConfig), {
publicPath: "http://localhost:8083/static/js/build/",
stats: {
colors: true
},
inline: true,
hot: true,
historyApiFallback: true,
contentBase: 'http://localhost:5000/'
}).listen(8083, "localhost", function(err) {
if(err) throw new PluginError("webpack-dev-server", err);
log("[webpack-dev-server]",
"http://localhost:8083/webpack-dev-server/index.html");
});
});
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var DEBUG = true;
module.exports = {
entry: [
__dirname + '/a/scripts/index'
],
output: {
path: __dirname + '/a/static/js/build',
filename: 'bundle.js',
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({sourceMap: false,
output: {comments: false}}),
],
resolve: {
extensions: ['.js', '.jsx'],
modules: ['node_modules', 'web_modules', 'scripts', 'lib'],
},
module: {
rules: [
{
test: /\*.js.x?$/,
exclude: /node_modules/,
loaders: (DEBUG ? ['react-hot-loader/webpack'] : []).concat(['babel-loader'])
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=image/svg+xml" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]=" +
path.resolve(__dirname, "./a/static/scss/")
}
]
},
externals: {
"jquery": "jQuery"
}
};
index.js
'use strict';
var React = require('react'),
Router = require('react-router'),
routes = require('routes');
// set up in order to receive actions
var NotificationStore = require('stores/NotificationStore');
require('csrf'); // injects CSRF token into all $.ajax calls
require('../static/scss/playground.scss'); // loads stylesheet into JS
Router.run(routes, Router.HistoryLocation, function(Handler) {
React.render(<Handler />, document.getElementById('entry'));
});
This issue is due to your babel setup. You need to install babel-plugin-transform-react-jsx and adjust your .babelrc file. Like this:
{
"presets": ["env", "es2015", "react"],
"plugins": ["transform-react-jsx", "transform-object-rest-spread"]
}
example webpack.config.js:
const path = require('path')
const config = {
entry: {
app: ['whatwg-fetch','./src/index.js'],
},
devtool: 'inline-source-map',
devServer: {
contentBase: './public'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
{
test: /\.css/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
]
},
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'public')
}
}
module.exports = config
example package.json:
{
"name": "react-news-app",
"version": "1.0.0",
"description": "get news and sentiment from headline articles",
"main": "index.js",
"scripts": {
"test": "jest --watch",
"start": "webpack-dev-server --port 3000"
},
"keywords": [
"api",
"react"
],
"author": "Stephen Collins",
"license": "MIT",
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"whatwg-fetch": "^2.0.3"
},
"devDependencies": {
"babel-jest": "^22.0.4",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.6.1",
"chai": "^4.1.2",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.8",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.15.0",
"eslint-loader": "^1.9.0",
"jest": "^22.0.4",
"prop-types": "^15.6.0",
"sinon": "^4.1.3",
"style-loader": "^0.19.1",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.10.0"
}
}
I was trying to add bootstrap in my new React project.
After running npm install bootstrap and react-bootstrap, i run webpack in my project and i get this Error : What could be the problem ?
/home/dove/projects/yulu/node_modules/loader-runner/lib/loadLoader.js:35
throw new Error("Module '" + loader.path + "' is not a loader (must have normal or pitch function)");
^
Error: Module '/home/dove/projects/yulu/node_modules/url/url.js' is
not a loader (must have normal or pitch function)
at loadLoader (/home/dove/projects/yulu/node_modules/loader-runner/lib/loadLoader.js:35:10)
at iteratePitchingLoaders (/home/dove/projects/yulu/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
at runLoaders (/home/dove/projects/yulu/node_modules/loader-runner/lib/LoaderRunner.js:362:2)
at NormalModule.doBuild (/home/dove/projects/yulu/node_modules/webpack/lib/NormalModule.js:181:3)
at NormalModule.build (/home/dove/projects/yulu/node_modules/webpack/lib/NormalModule.js:274:15)
at Compilation.buildModule (/home/dove/projects/yulu/node_modules/webpack/lib/Compilation.js:149:10)
at factoryCallback (/home/dove/projects/yulu/node_modules/webpack/lib/Compilation.js:337:12)
at factory (/home/dove/projects/yulu/node_modules/webpack/lib/NormalModuleFactory.js:241:5)
at applyPluginsAsyncWaterfall (/home/dove/projects/yulu/node_modules/webpack/lib/NormalModuleFactory.js:94:13)
at /home/dove/projects/yulu/node_modules/tapable/lib/Tapable.js:268:11
at NormalModuleFactory.params.normalModuleFactory.plugin (/home/dove/projects/yulu/node_modules/webpack/lib/CompatibilityPlugin.js:52:5)
at NormalModuleFactory.applyPluginsAsyncWaterfall (/home/dove/projects/yulu/node_modules/tapable/lib/Tapable.js:272:13)
at resolver (/home/dove/projects/yulu/node_modules/webpack/lib/NormalModuleFactory.js:69:10)
at process.nextTick (/home/dove/projects/yulu/node_modules/webpack/lib/NormalModuleFactory.js:194:7)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports =
{
entry :{
app :'./app/app.jsx',
},
output :{
path : __dirname,
filename: './client/bundle.js'
},
resolve :{
alias : {
//Utilities: path.resolve(__dirname, 'src/utilities/'),
//Templates: path.resolve(__dirname, 'src/templates/')
},
extensions : ['.js','.jsx']
},
module :{
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
},
exclude :/(node_modules|bower_components)/
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
},
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
]
}
}
my package.json
{
"name": "yulu",
"version": "1.0.0",
"description": "This is a business advertising website",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "#magic wand",
"license": "MIT",
"dependencies": {
"bootstrap": "^3.3.7",
"express": "^4.15.4",
"react": "^15.6.1",
"react-bootstrap": "^0.31.2",
"react-dom": "^15.6.1",
"react-router": "^4.1.2"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"exports-loader": "^0.6.4",
"file-loader": "^0.11.2",
"imports-loader": "^0.7.1",
"node-sass": "^4.5.3",
"postcss-loader": "^2.0.6",
"resolve-url-loader": "^2.1.0",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"url-loader": "^0.5.9",
"webpack": "^3.5.4"
}
}
Since wepack 2 it's no longer allowed to omit the -loader suffix and the loaders are resolved literally. In your case it uses the npm package url, which might be a dependency of one of your dependencies. That package is not a valid loader and therefore fails.
The affected rules need to be changed to:
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
}