How to fix “Module build failed: SyntaxError: Unexpected token” error when using JSON file in react? - json

I am following a react tutorial by Brian holt and i need to import .json file inside my react component like this :
code
When I try to build my project i was getting
ERROR in ./data.json
Module build failed: SyntaxError: Unexpected token, expected
like this:
Error caption in terminal
at first i thought that it was an eslint issue but it seems that it happens on the build step, i tried adding a json-loader to webpack but without any success.
Webpack Version:
2.6.1
Babel Core Version:
6.24.1
Babel Loader Version:
7.0.0,
this is my webpack config file :
const path = require('path')
module.exports = {
context: __dirname,
entry: './js/clientApp',
devtool: 'cheap-eval-source-map',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/assets/'
},
resolve: {
extensions: ['.js', '.jsx', ',json']
},
devServer: {
publicPath: '/public/',
port: 2110,
open: true,
historyApiFallback: true
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
enforce: 'pre',
test: /\.jsx?/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
test: /\.jsx?/,
loader: 'babel-loader'
}
]
}
}
and this is my .babelrc file :
{
"presets": [
"react", ["env", {
"targets": {
"browsers": "last 2 versions"
},
"loose": true,
"modules": false
}]
]
}
Any suggestions please ?

Regular Expression
The test property identifies which file or files should be transformed.
The problem is the regular expression on your rules:
{ test: /\.jsx?/ }
Your telling webpack to use babel-loader with any file extension starting with .js or .jsx
So as you can see .json match the test.
Solution
$ - matches anything until the end of the string
To fix this just replace ? with $, see the example below:
module: {
rules: [
{
test: /\.jsx$/,
loader: 'babel-loader'
}
]
}

Related

Trying to ''npm start" my vue.js build, but i get this error: This relative module was not found:

I'm trying to use node.js as my server and vue.js as my client side.
I'm building a chat application with both, with integrated stuff like Axios, Express, Sequelize and vuetify.
The project has been silent for a week of 2 due to a few complications.
I tried to start it back up again and i got this error on my server side:
ERROR Failed to compile with 1 errors 4:25:16 PM
This relative module was not found:
./src/main.js in multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js
I've tried to change paths, restart servers and recreate files.
I'm quite new to Vue, so i have no clue what to do and i couldn't find an appropriate answer anywhere.
Here is the webpack.base.conf file
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)
}
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
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: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
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('img/[name].[hash:7].[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('fonts/[name].[hash:7].[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'
}
}```
It should just start the build like a regular app, but sadly.

Webpack 4 html partials resolve images in files

I am new to webpack, I followed directions in this link https://github.com/hardikkaji/angularjs-es6-starter-kit
I am using webpack 4 with angular 1.7
I am not able to resolve images.
ERROR in ./node_modules/angular-datatables/demo/basic/overrideLoadingTpl.html
Module not found: Error: Can't resolve './images/loading.gif' in '/home/user/workspace/webpack/angular-webpack/node_modules/angular-datatables/demo/basic'
My webpack.config.js is below
const config = {
mode: devMode ? 'development' : 'production',
entry: {
'vendor': './frontend/vendor.module.js', //seperates all 3rd party plugins like ui-router, retstangualr etc
'app': './frontend/index.main.js' //main entry point for angular js
},
devtool: devMode ? 'source-map': 'none',
output: {
filename: elixirConfig.js.outputFolder + '/[name].[hash].bundle.js',
//filename: 'libs/[name].[hash].bundle.js', //where to store the generated files all files will be generated inside a folder called libs
//path: path.resolve(__dirname, 'build')
path: path.resolve(__dirname, elixirConfig.buildPath)
},
module: {
rules: [
{
test: /.js$/, //check for file that ends with .js extension
exclude: /node_modules/, //do not check for files inside node_modules folder
loader: ['ng-annotate-loader', 'babel-loader'],
//presets: ['es2016'],
},
{
test: /.(scss)$/, //check for files that end with scss
use: [
devMode ? { loader: "style-loader" } : MiniCssExtractPlugin.loader,
{ loader: "css-loader", options: { minimize: true } },
{ loader: "sass-loader" },
]
},
// for fixing of loading bootstrap icon files
{
test: /.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000',
options: {
name: './fonts/[name].[ext]'
}
},
{
test: /.(woff(2)?|ttf|eot|svg)(\?v=\d+.\d+.\d+)?$/,
loader: 'file-loader',
options: {
name: './fonts/[name].[ext]'
}
},
{ test: /.html$/, include: /node_modules/, loader: 'html-loader' },
]
},

I am using Angular 6 and need to convert all scss files to rtl-css files

I have used angular builders and created custom webpack.config.js
I am trying to use webpack-rtl-plugin.
Following are my custom-webpack.config.js
module.export = {
entry: {
app: path.join(__dirname, './src/main.ts')
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src')
},
{
test: /\.scss$/,
// for dev we simply use the style-loader combined with
// the rtl-css loader
loaders: ['style-loader', 'rtl-css-loader']
}
]
}
};
But I am getting Following error
Invalid CSS after "": expected 1 selector or at-rule, was "var content = requi"
What is the cause of this? Any alternate solutions?

WebPack Cache busting hash in file names never changes

I am trying to get cache busting in my gulp file output to work. Currently it outputs a file like this: main.2d06434c1c57525870ac-e7615836.js but whenever I modify typescript files and rebuild the hash in the file name output is always the same.
I have tried the built in webpack hashing and the gulp vinyl-named hashing to see if there was something wrong with one of their configurations but again their output filename is the same on each rebuild.
Here is the related part of my builder task. Thanks!
var packer = gulp.src(['./src/basePolyfills.ts', './src/external.ts', './src/main.ts'])
.pipe(named())
.pipe(webpack({
output: { filename: '[name].[hash].js' },
module: {
loaders: [
{ test: /\.ts$/, loader: 'ts' },
{ test: /\.html$/, loader: 'html' }
]
},
resolve: { extensions: ['', '.js', '.ts'] }
}))
.pipe(hash())
.pipe(gulp.dest('./wwwroot/js/'));
Where is your hash() coming from? As far as I know, webpack automatically calculates chunkhashes. Be aware that there is a difference between "hash" and "chunkhash". chunkhash is a hash per chunk, whereas "hash" seems to be a hash over all files.
Can you try:
var packer = gulp.src(['./src/basePolyfills.ts', './src/external.ts', './src/main.ts'])
.pipe(named())
.pipe(webpack({
output: { filename: '[name].[chunkhash].js' },
module: {
loaders: [
{ test: /\.ts$/, loader: 'ts' },
{ test: /\.html$/, loader: 'html' }
]
},
resolve: { extensions: ['', '.js', '.ts'] }
}))
.pipe(gulp.dest('./wwwroot/js/'));

How to use pixi.js with gulp and webpack including FXAA

I just started pixi.js and it seems marvelous!
But I can't make it totally work with Gulp and WebPack...
On Chrome (Mac), everything work but on Safari (iPhone) i get this error: fs.readFileSync is not a function from function FXAAFilter.
I get the same error on desktop when I use forceFXAA: true.
My gulp scripts task :
gulp
.src(config.scripts.src)
.pipe(gulp_webpack({
node: {
fs: "empty"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(nodes_modules)/,
loader: "babel-loader",
query: {
presets: ["es2015"]
}
},
{
test: /\.json$/,
loader: "json"
}
],
postLoaders: [
{
include: path.resolve(__dirname, "nodes_modules/pixi.js"),
loader: "transform?brfs"
}
]
},
}))
.pipe(gulp_concat(config.scripts.out))
.pipe(gulp.dest(config.scripts.dst));
This is because webpack includes the actual file operation (that should be run at compile time) that is used to include WebGL frag files into the JS bundle. My guess is that you only see the error on environments where PIXI uses the GL renderer.
Try npm install transform-loader brfs --save and add the following to your config:
module.exports = {
context: __dirname,
entry: "./index.js",
module: {
loaders: [
{
test: /\.js$/,
loader: "transform?brfs"
}
]
}
}
Source: https://github.com/webpack/transform-loader