Babel convert path jsx to js - reactjs

I am using babel to transpile some es2015 code to es5, like this:
"scripts": {
"build:lib": "babel src --out-dir lib --presets=react,es2015,stage-0",
"clean": "rimraf lib dist coverage",
"prepublish": "npm run clean && npm run build:lib"
}
It is converting it fine to es5. The problem is that babel is not changing the path among files. It changes the extension of the file from .jsx to .js, but inside the file, it is still referencing the file as .jsx.
To simplify it, the folder structure looks like this. Babel has changed the extensions of the .jsx files:
- index.js
- Component.js
While inside index.js, it is doing keeping the .jsx extension:
require('./Component.jsx');
Am I missing something? Is there a better way to do this?
Thanks for you help:)

Why won't you simply use Webpack for that? Is there a reason for that? especially that you are also missing setting up node_env production so it will avoid adding propTyping etc.
es3ify is just for changing the code, while you are trying to build a library out of it. you need a tree builder like Webpack for something like that (how es3ify would know about the references between each other?)
So tl;dr there is a better solution for that: use Webpack.
module.exports = {
devtool: 'source-map',
entry: [
path.join(__dirname, '/src/index.jsx')
],
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
};

As Shiroo suggested, I ended up using webpack for this. The key concept here was understanding what resolvers do. They are really well explained in the webpack docs: https://webpack.github.io/docs/resolving.html
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js', '.jsx']
}
Later, I encountered that all the node_modules were also included in the bundle, despite having it explicitly inside the loader:
module: {
loaders: [
{
test: /(\.jsx|\.js)$/,
include: path.resolve('./src'),
exclude: /node_modules/,
loader: 'babel'
}
]
}
This issue is better explained here https://stackoverflow.com/a/35820388/4929834

Related

How can I resolve this issue about Storybook and Sass?

I have an issue about Storybook. I can't start storybook and I have an error about my SCSS file.
Here is the error:
ModuleParseError: Module parse failed: Unexpected token (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
.h1 {
| color: red;
| }
at handleParseError (/myproject/node_modules/#storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:469:19)
I mean this is juste a simple class. But when the file is empty, the compilation is okay, so I don't understand how I can resolve this.
My SCSS file
.h1 {
color: red;
}
My Webpack file
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, './src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.scss?$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
hot: true,
},
};
My main.js file in the .storybook folder
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)",
"../src/**/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
]
}
Is anyone has a solution please?
Thanks by advance
Finally, I have solved my problem, so here is how I did it.
First of all, I uninstalled the storybook (How to remove storybook from the react project), then the reinstalled via webpack (https://storybook.js.org/blog/storybook-for-webpack-5/).
For once with Webpack it works whereas installing it with NPM (or Yarn for my part) brought me to the complications that I had posted above. My guess is that it works for Webpack 5, whereas with NPM, I was getting an error about the css-loader loader that told me about Webpack 4.
Storybook worked, but I was still worried about .scss files. My terminal told me that I did not have a specific loader. So I took a loader for this type of file by adding a webpack.config.js in the .storybook folder created when we install Storybook. I used the instructions found here: https://storybook.js.org/docs/react/configure/webpack
About Sass files: Storybook is case sensitive, and also doesn't take into account files starting with _, so not possible to use partials
I hope you don't have this kind of problem, but if you do, maybe these answers will help you ^^

Webpack cannot identify my JSX syntax inside my js file

When i try to bundle my modules with webpack, it cannot identify the JSX syntax inside my index.js file and gives the following error:
ERROR in ./src/index.js 29:3
Module parse failed: Unexpected token (29:3)
You may need an appropriate loader to handle this file type.
| const searchTerm = _.debounce(term => {this.searchTerm(term)}, 300);
| return (
> <div>
| <SearchBar onInputChange= {searchTerm}/>
| <div className="row">
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js main[1]
This is my webpack config:
const Path = require('path');
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: Path.resolve(__dirname, '../src'),
use: {
loader: 'babel-loader',
options: {
presets: ["#babel/preset-react", "#babel/preset-env"]
}
}
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [ 'css-loader' ]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './',
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
}
};
I have added the babel presets for react namely #babel/preset-react. I have also added the babel-loader but still it cannot identify the JSX syntax.
I cloned your repo and found a bunch of conflicts on your code setup.
Some of your packages are not aligned with the latest versions of your #babel/core package. If you are going to use the latest version of babel, might as well use the latest presets.
`
devDependencies: {
#babel/cli: ^7.0.0,
#babel/core: ^7.0.0,
#babel/preset-env: ^7.0.0,
#babel/preset-react: ^7.0.0,
babel-loader: ^8.0.0"
}
`
and I removed babel-preset-env and babel-preset-react (the old versions) on your dependencies.
Pick one babel configuration. It's either on your package.json or on .babelrc. I suggest you stick with the .babelrc file. And changed the values of the presets property.
`"presets": ["#babel/preset-react", "#babel/preset-env"],`
On your webpack.config.js you don't need to do include: include: Path.resolve(__dirname, './src'). You can also remove this line:
`presets: ["react", "env"]`
and BTW, on your package.json,
"scripts": {
- "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
+ "start": "webpack-dev-server --mode development",
...
when you run npm start your project will look into a locally installed webpack-dev-server and use the global one if it does not find the local package.
Hope this helps. :)

Webpack: Can I get a source map for after babel, before minification?

I have a fairly basic webpack setup that runs babel and out comes my minified js with a source map.
Now when I run my source map in chrome I get the js before babel and before minification. However I would often like to have my source map after babel but before minification. Is this possible?
TL;DR I want source map to post-babel pre-minifcation. Possible?
For completeness
I run babel-loader 8 with webpack 4
Here is a screenshot from chrome showing the problem. As you can see the Dropzone tag indicates this is jsx (and so before babel)
Secondly here is my webpack config (not that it actually matters for my question).
const path = require('path');
module.exports = {
context: path.join(__dirname, 'Scripts', 'react'),
entry: {
client: './client'
},
output: {
path: path.join(__dirname, 'Scripts', 'app'),
filename: '[name].bundle.min.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
plugins: [require('#babel/plugin-proposal-object-rest-spread')],
presets: ["#babel/es2015", "#babel/react", "#babel/stage-0"]
}
}
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
externals: {
// Use external version of React (from CDN for client-side, or
// bundled with ReactJS.NET for server-side)
react: 'React'
},
devtool: 'source-map'
};
Running webpack with -d gives a second set of source maps in chrome that does the trick.

Webpack production build file paths are off

I'm running this command to try & generate a production webpack build:
rimraf ./build/* && webpack -p --progress --config webpack.production.js
However, when I open up the build/index.html, it's failing to load a lot of files because the locations are off.
It fails to put the correct location for the bundle.js file. It loads it like this: /bundle.js. However the bundle.js file is actually in the same directory as the index.html file in the build folder so it should load it like this ./bundle.js
If I correct the bundle.js path, it's still putting an incorrect route for the assets:
What's interesting is that my app currently works with the webpack dev server when I run: webpack-dev-server --inline --progress --config webpack.dev.js.
Here is what my current webpack.production.js file looks like:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'source-map',
devServer: {
historyApiFallback: true, // This will make the server understand "/some-link" routs instead of "/#/some-link"
},
entry: [
'./src/scripts' // This is where Webpack will be looking for the entry index.js file
],
output: {
path: path.join(__dirname, 'build'), // This is used to specify folder for producion bundle
filename: 'bundle.js', // Filename for production bundle
publicPath: '/'
},
resolve: {
modules: [
'node_modules',
'src',
path.resolve(__dirname, 'src/scripts'),
path.resolve(__dirname, 'node_modules')
], // Folders where Webpack is going to look for files to bundle together
extensions: ['.jsx', '.js'] // Extensions that Webpack is going to expect
},
module: {
// Loaders allow you to preprocess files as you require() or “load” them.
// Loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle frontend build steps.
loaders: [
{
test: /\.jsx?$/, // Here we're going to use JS for react components but including JSX in case this extension is preferable
include: [
path.resolve(__dirname, "src"),
],
loader: ['react-hot-loader']
},
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
include: [
path.resolve(__dirname, "src"),
],
// Only run `.js` and `.jsx` files through Babel
test: /\.jsx?$/,
// Options to configure babel with
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0', 'react'],
}
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(), // Webpack will let you know if there are any errors
// Declare global variables
new webpack.ProvidePlugin({
React: 'react',
ReactDOM: 'react-dom',
_: 'lodash'
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
hash: true
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
]
}
And just in case, this is what my current webpack.dev.js file looks like:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-source-map',
devServer: {
historyApiFallback: true, // This will make the server understand "/some-link" routs instead of "/#/some-link"
},
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://127.0.0.1:8080/', // Specify the local server port
'webpack/hot/only-dev-server', // Enable hot reloading
'./src/scripts' // This is where Webpack will be looking for the entry index.js file
],
output: {
path: path.join(__dirname, 'build'), // This is used to specify folder for producion bundle
filename: 'bundle.js', // Filename for production bundle
publicPath: '/'
},
resolve: {
modules: [
'node_modules',
'src',
path.resolve(__dirname, 'src/scripts'),
path.resolve(__dirname, 'node_modules')
], // Folders where Webpack is going to look for files to bundle together
extensions: ['.jsx', '.js'] // Extensions that Webpack is going to expect
},
module: {
// Loaders allow you to preprocess files as you require() or “load” them.
// Loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle frontend build steps.
loaders: [
{
test: /\.jsx?$/, // Here we're going to use JS for react components but including JSX in case this extension is preferable
include: [
path.resolve(__dirname, "src"),
],
loader: ['react-hot-loader']
},
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
include: [
path.resolve(__dirname, "src"),
],
// Only run `.js` and `.jsx` files through Babel
test: /\.jsx?$/,
// Options to configure babel with
query: {
plugins: ['transform-runtime', 'transform-decorators-legacy'],
presets: ['es2015', 'stage-0', 'react'],
}
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // Hot reloading
new webpack.NoEmitOnErrorsPlugin(), // Webpack will let you know if there are any errors
// Declare global variables
new webpack.ProvidePlugin({
React: 'react',
ReactDOM: 'react-dom',
_: 'lodash'
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
hash: false
})
]
}
Any ideas what I'm doing wrong?
faced a similar issue. setting output.publicPath: "/" in webpack.dev.js and output.publicPath: "./" in webpack.prod.js, did the trick for me.
Got the same error when running npm run watch, local dev still worked, but after deploying to demo server the app crashed on wrong js-file url.
Cause:
Some changes in my webpack.mix.js started compiling a index.html file that was found by the browser, instead of the app.blade I was using.
Fixed the paths by setting: publicPath: './public/'
(Note that it's a relative path). Also, I removed the generated url by setting inject: false, in the HtmlWebpackPlugin({ section and used the asset('/...') logic.

react with webpack gives me a massive bundle.js file

Ok I have read many posts(like this one) on here about optimizing bundle.js for a production build but they are not changing my bundle.js file at all so I must be doing something wrong. I am building with the command:
webpack -p --config webpack.production.config.js
and webpack.production.config.js looks like this:
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: [
'./src/index.js'
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015']
}
]
},
alias: {
'react$': path.join(__dirname, 'node_modules', 'react','dist','react.min.js'),
'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist','react-dom.min.js')
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
};
I am at a loss. I have 17 node_modules including all the basics like react and webpack. My bundle.js file is 15.6MB....absolutely massive and unacceptable. From what I am reading it looks like the -p and this plug in
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
should automatically use the .min.js version of everything. Is that correct? Do I have to do anything to force my application to use that?
Any optimization would help tremendously! The application is not really that large and the initial load of the page is taking WAY to long.
Thanks!!
For a production build try changing devtool: 'inline-source-map' to devtool: 'source-map'
The webpack config from https://webpack.github.io/docs/configuration.html says:
inline-source-map - A SourceMap is added as DataUrl to the JavaScript
file.
Also, and again for production builds, you can remove 'react-hot' in the loaders section.
For example, with these differences in one of my projects the development bundle is 9MB but the production one is 600KB. Hopefully you'll see similar improvements.
I highly recommend you read this tutorial,the answer is very obvious after reading this.
Put simply ,you can use a plugin named uglify which can reduce the bundle size dramatically.
In addition, 'NODE_ENV': JSON.stringify('production') is used by React ,nothing to do with webpack

Resources