I have a project with multiple apps and some common react components in this structure:
ui
- app1
- app2
- components
The javascript files in components are written in ES6. Both app1 and app2 have this webpack config:
var path = require('path')
module.exports = {
entry: ['babel-polyfill', './src/index.js'],
module: {
rules: [{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, '../components'),
path.resolve(__dirname, 'src')
],
loader: 'babel-loader'
}]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
alias: {
InputComponents: path.resolve(__dirname, '../components'),
}
},
}
Babel config:
{
"plugins": [
"transform-async-to-generator",
"glamor/babel"
],
"presets": [
"es2015",
"react",
"stage-0"
]
}
My code:
import React, { Component } from 'react'
import { Button } from 'CommonComponents'
export default class ButtonView extends Component {
render () {
return <Button>GO!</Button>
}
}
I want my components and my apps to be built and transpiled to ES5 using Babel. The apps work but not the external components and I get errors like:
Module build failed: SyntaxError: Unexpected token (6:34)
4 | class Button extends Component {
5 | render () {
> 6 | if (this.props.stroke) return <ButtonStroke {...this.props} />
| ^
How can I make sure that babel transpiles my external components?
Related
I am developing a npm package and use there webpack 5.
This is my config
const path = require('path') // resolve path
module.exports = {
mode: 'development',
resolve: {
extensions: ['.js', '.jsx'], // we can import without typing '.js or .jsx'
},
entry: {
index: path.join(__dirname, 'src/index.jsx'),
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index.js', // for production use [contenthash], for developement use [hash]
library: {
type: 'module',
},
environment: { module: true },
},
experiments: {
outputModule: true,
},
devtool: 'eval',
module: {
rules: [
{
test: /\.(css|scss|sass)$/,
use: [
{
loader: 'style-loader', // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'sass-loader', // compiles Sass to CSS
},
],
},
{
test: /\.(js|jsx)$/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(png|svg|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
{
test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
exclude:
/images/ /* dont want svg images from image folder to be included */,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts/',
name: '[name][hash].[ext]',
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
plugins: [],
}
When I want to import components from this library I get this error:
Failed to resolve import "React" from "..my-package/dist/index.js". Does the file exist?
I think this has something to do with externals react and react-dom. But when I remove the externals from webpack config I get the error that react should be only installed once when using react hooks.
In my main application I am using vite for bundeling but I tried it also with create-react-app and have the same problem.
My Library Component:
import React, { useState } from 'react'
const App = () => {
const [counter, setCounter] = useState(0)
return <div>{counter}</div>
}
export default App
This is how I am using it with npm-link:
import React from "react";
import Test from "my-package";
const App = () => {
return <Test />;
};
export default App;
Here is the repo with the code https://github.com/guitar9/webpack-bug
I am learning how to make custom component or library and publish on npm. I found a free tutorial here:
https://www.udemy.com/course/your-custom-react-component/learn/lecture/13561884#overview
github link
https://github.com/davidcsejtei/custom-button
But I am facing one problem .he created a simple component custom button
import React, { Component } from 'react';
import '../style/button.scss';
export default class CustomButton extends Component {
render() {
return(
<button>Custom button</button>
);
}
}
but when we create a build it include react library in his build so now it's size increase to 7.5kb.It should be below 2kb as it is small component and it is used in another project
In other ways custom component use react dependency from there parent component . Can we remove this react dependency in build ?
Here is the webpack config:
const webpack = require('webpack');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'custom-button.js',
library: 'custom-button',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
}
]
},
optimization: {
minimizer: [new UglifyJsPlugin()]
},
plugins: [
new CleanWebpackPlugin(['dist'])
]
}
any update ?
In order to exclude react out of your build with webpack, you just simply declare externals in your configuration like below:
externals: {
react: "react",
}
As you output with your umd module above, it will require react as the dependency in the build which means it will consume the react at the parent (consuming) repo:
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
// ...
How can I use React.js in the front-end of my AdonisJs project?
I've tried to install react with npm install react I thought this will works correctly. I made a file app.js with this code:
var React = require('react');
var ReactDOM = require('react-dom');
export default class Index extends Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'))
But this isn't working at all, I don't know what to do more I have searched about how to use React in Adonis but I didn't find anything interesting.
I strongly suggest you to use WebPack for this task.
create a webpack.config.js file in your root directory:
maybe your code need some changes but this is the idea:
const webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var pkgBower = require('./package.json');
module.exports = {
target: "web",
devtool: "source-map",
node: {
fs: "empty"
},
entry: {
'app': path.join(__dirname, 'react-app', 'Index.jsx')
},
resolve: {
modules: [__dirname, 'node_modules', 'bower_components'],
extensions: ['*','.js','.jsx', '.es6.js']
},
output: {
path: path.join(__dirname, 'public', 'src'),
filename: '[name].js'
},
resolveLoader: {
moduleExtensions: ["-loader"]
},
module: {
loaders: [
{
test: /jquery\.flot\.resize\.js$/,
loader: 'imports?this=>window'
},
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-0'],
compact: false
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
loader: 'url?prefix=font/&limit=10000'
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url?limit=10000'
},
{
test: /\.scss$/,
loader: 'style!css!sass?outputStyle=expanded'
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new CopyWebpackPlugin([{
from: 'img',
to: 'img',
context: path.join(__dirname, 'react-app')
}, {
from: 'server',
to: 'server',
context: path.join(__dirname, 'react-app')
}, {
from: 'fonts',
to: 'fonts',
context: path.join(__dirname, 'react-app')
}]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
mangle: true,
sourcemap: false,
beautify: false,
dead_code: true
}),
new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /js$/)
]
};
Then put your app in your root directory, in a folder react-app/ and your components can go inside that folder:
For example your file: [Index.jsx]
import React from 'react';
import ReactDOM from 'react-dom';
class Index extends Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'));
you don't need to export this Index component in this case, but in case you need to just use export default ComponentName at the end of your component file.
The next step is in your routes file (I'm using AdonisJS 4) but is very similar for the version 3.x
Route.any("*", ({ view, response }) => (
view.render('index')
))
Then your index (.njk, or .edge) file (under resources/views) should look something like this:
<html>
<head>
<link rel="stylesheet" href="/src/styles.css">
<script type="text/javascript" src="/src/app.js"></script>
</head>
<body>
<div id="example"></div>
</body>
</html>
--
You need to install some npm/ packages with npm or yarn,
and remember to run in another terminal window or tab,
webpack -d --watch --progress
Regards.
This works. You are missing React.Component.
var React = require('react');
var ReactDOM = require('react-dom');
export default class Index extends React.Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'))
Alternatively you can use import React, {Component} from 'react'; if you want to use your code structure.
For decoupled use, just build your React app and copy the build to Adonis public folder.
I have 3 files, which look like this:
util/index.ts
export * from './Vector2'
export * from './Sprite'
export * from './GameObject'
export * from './Component'
util/Component.ts
export interface ComponentType<T extends Component> {
new(gameObject: GameObject): T;
}
export class Component { }
components/Rigidbody.ts
import { Component } from '../util'
export class Rigidbody extends Component { }
Everything works fine in the editor, and when the code compiles into javascript. However, when I run the code in the browser, I get the error:
Uncaught TypeError: Class extends value undefined is not a constructor or null
Which is referring to export class Rigidbody extends Component
If I change my import to import the Component file instead of the index file it works:
import { Component } from '../util/Component'
I also have a Transform file that imports the Component file, and that one does the same thing.
Is there something I am doing wrong or is it the way I am building it with webpack?
Here is my webpack file:
const path = require('path')
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
PIXI: path.join(__dirname, 'node_modules/pixi.js/lib/index.js')
}
},
output: {
libraryTarget: 'var',
library: 'phoenix',
filename: 'phoenix.js',
path: path.resolve(__dirname, 'dist')
}
};
I'm creating a small component library for react. Something that can be required like var Components = require('components'). This will have individual components, much like react-bootstrap does. I'm trying to use webpack with babel to compile this into an index.js file. The compilation went well. I published this to my local npm registry and installed it in one of my other projects. When I require it - require('components') - the require returns an empty object. Below is my folder structure
root
|- components
| |- ImageEditor.js
|
|- lib
| |- index.compiled.js (file compiled by webpack)
|
|- index.js (requires ./components/ImageEditor.js, entry point for webpack)
|- webpack.config.js
ImageEditor.js
import React from 'react';
import ReactDOM from 'react-dom';
import Canvas from './utils/canvas';
import '../stylesheets/imageeditor.scss';
class ImageManipulation extends React.Component {
static propTypes = {};
state = {
height: 200,
width: 200,
scale: 1.25
};
static defaultProps = {
color: [213, 214, 217, 0.6],
image: ""
};
...
render() {
return (
<div className="_react-image-manipulation">
<div className="_cover-box">
{ this.loadComponent() }
</div>
</div>
);
}
}
export default ImageManipulation;
index.js
import ImageEditor from './components/ImageEditor';
export default {
ImageEditor
};
webpack.config.js
var path = require('path');
var NODE_ENV = process.env.NODE_ENV || 'development';
var WebpackNotifierPlugin = require('webpack-notifier');
var UglifyJSPlugin = require("webpack/lib/optimize/UglifyJsPlugin");
var CleanWebpackPlugin = require("clean-webpack-plugin");
var commonPlugins = [
new WebpackNotifierPlugin({
title: 'Contour Components'
})
];
function getPlugins() {
if (NODE_ENV == 'prod') {
commonPlugins.push(new CleanWebpackPlugin(['lib/*']));
commonPlugins.push(new UglifyJSPlugin({
compress: {
warnings: false
}
}));
}
return commonPlugins;
}
module.exports = {
devtool: 'sourcemap',
entry: {
index: './index.js'
},
output: {
path: path.join(__dirname, 'public'),
filename: '[name].compiled.js'
},
plugins: getPlugins(),
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
query: {
cacheDirectory: true,
presets: ['es2015', 'stage-0', 'react'],
plugins: ['add-module-exports', "transform-class-properties"]
},
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.png$/,
loader: "url-loader?limit=100000&mimetype=image/png"
}, {
test: /(\.scss|\.css)$/,
include: /components/,
loader: 'style!css!sass'
}]
},
resolve: {
extensions: ['', '.scss', '.js', '.json', '.png'],
modulesDirectories: [
'node_modules',
'components'
]
}
};
Any idea what I'm doing wrong here?
You are exporting component in the object in the default export.
Babel 6 produces the following CommonJS module for you. See REPL:
exports.default = {
ImageEditor: ImageEditor
};
Then you can use this component like this:
var ImageEditor = require('my-lib').default.ImageEditor
Your component is hidden under the default key. If you don't want it, use named exports instead.
export {ImageEditor};
For this, Babel produces the following code
exports.ImageEditor = ImageEditor;
Look, no extra default key, and everything work as expected