I've built a wrapper package for drag and drop in React, and I added storybook examples.
Since in my consumer React is exposed globally, i'm not importing React explicitly.
In the storybook examples I need to supply React as part of the custom webpack config, but for some reason it can't resolve React and I get a ReferenceError: React is not defined
This is the package - https://github.com/fiverr/drag_n_drop_package
And this is the custom webpack config file:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.ProvidePlugin({
React: 'react'
})
],
module: {
loaders: [
{
test: /\.scss$/,
loader: 'style!raw!sass'
}
]
}
};
This is really strange but your storybook webpack.config.js is mixing webpack v1/v2.
Importing webpack as
const webpack = require('#kadira/storybook/node_modules/webpack');
solves it because it uses the same webpack reference that storybook is using (v1).
I found the following code in webpack.config.js at github:
externals: {
react: 'React'
}
It looks as this question. If it needs to load the React lib from external, like CDN. The page has to be sure have a script tag for importing React lib. And make sure this script tag is in front of the bundle.js or the file which it generated by webpack, so the Object of React will exist when the following code needs to use React, such as:
<script src="./react.js"></script>
<script src="./bundle.js"></script>
Related
I have a React component library that is used in a React app. The component library is setup using Styleguidist and webpack. I've setup webpack to use absolute paths using:
webpackConfig: {
resolve: {
modules: [path.resolve(__dirname, 'src/'), 'node_modules'],
}
}
This works within the context of the component library. When I build the component library, the package looks like this:
/core
/components
/Table
/Row
When I import the components into my app, I get an error:
Module not found: Can't resolve components/Row in /Users/myusername/Sites/mysite/node_modules/#mypackage/core/components/Table
I understand why the paths don't match in the context of node_modules, but I would've expected Webpack to transform those import paths during the build process. Is there something I'm missing? Or is this not possible?
While Styleguidist uses webpack, it turns out the build script we were using does not, so the webpack config is irrelevant. Instead, our build script (https://www.npmjs.com/package/cod-scripts) uses babel.
We ended up having to add a separate babel.config.js file to define absolute paths for babel using the babel-plugin-module-resolver package.
npm install babel-plugin-module-resolver --saveDev
npm install #babel/preset-react --saveDev
babel.config.js
module.exports = {
plugins: [
[
'module-resolver',
{
root: ['./src'],
},
],
],
presets: ['#babel/preset-react'],
};
I have my create-react-app bootstrap workspace setup to support module imports using #app/ as my root module.
I achieve this by adding this to my webpack config
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
'#app': path.resolve(__dirname, '../src')
},
However this does not seem to work with my jest tests. Anytime something is imported with #app the import is not resolved.
Anyone have a good solution to this
I have two project using webpack. Now I want to bring one project as module of other project. I can get the two bundle created but don't know how to import from the other bundle.
Elaborating a bit:-
Lets say the other file from which i want to import looks like as follows:-
index2.js (Bundled as bundleTwo)
import SomeCompoent from "./components/SomeCompoent/SomeCompoent";
module.exports = {SomeCompoent}
and in the file (is in another bundle - bundleOne) below I want to import the component (somecomponent):-
index1.js (in bundleOne)
import {SomeCompoent} from "bundleTwo";
but here bundleTwo is undefiend
Any help is highly appreciated
One way that I have figured out myself, is that using alias this can be achieved.
To make this line import {SomeCompoent} from "bundleTwo"; work, bundleTwo can be defined in alias :-
config:{
resolve: {
alias: {
"bundleTwo": path.join(__dirname, "<path_to_the_bundleTwo>")
}
....
If you want to use webpack only,then just set the libraryTarget to 'umd' in bundletwo webpack configuration.
In order to be able to import this module, you need to export your bundle.
output: {
libraryTarget: 'umd',// make the bundle export
filename: "index.js",
path: path.resolve(__dirname, "dist"),
}
However, this can also be achieved by just using Babel to transpile your ES6 code to ES5 code.
babel index2.js --out-file dist/index2.js
Now set the main in package.json to "dist/index2.js"
Now you can use it like
import {SomeCompoent} from "bundleTwo";
You can also create a gulp script for that
gulp.task('js', function () {
return gulp.src(['packages/**/*.js', "!**/*.test.js"])
.pipe(babel({
plugins: ['transform-runtime']
}))
.pipe(gulp.dest('dist'));
});
I have a directory structure like this:
and inside node_modules:
>node_modules
>./bin
>webpack.config.js
>bootstrap
>bootstrap.css
>bootstrap.js
I need to generate separate CSS and JS bundles like this:
custom-styles.css, custom-js.js, style-libs.css, js-libs.js
where style-libs and js-libs should contain syles and js files of all libraries like bootstrap and jQuery. Here's what I have done so far:
webpack.config.js:
const path = require('path');
const basedir = path.join(__dirname, '../../client');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const stylesPath = path.join(__dirname, '../bootstrap/dist/css');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
watch: true,
// Script to bundle using webpack
entry: path.join(basedir, 'src', 'Client.js'),
// Output directory and bundled file
output: {
path: path.join(basedir, 'dist'),
filename: 'app.js'
},
// Configure module loaders (for JS ES6, JSX, etc.)
module: {
// Babel loader for JS(X) files, presets configured in .babelrc
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
babelrc: false,
query: {
presets: ["es2015", "stage-0", "react"],
cacheDirectory: true // TODO: only on development
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
]
},
// Set plugins (for index.html, optimizations, etc.)
plugins: [
// Generate index.html
new HtmlWebpackPlugin({
template: path.join(basedir, 'src', 'index.html'),
filename: 'index.html'
}),
new ExtractTextPlugin(stylesPath + "/bootstrap.css", {
allChunks: true,
})
]
};
Client.js
import * as p from 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
I am able to run the app and render all of the components correctly except loading the external JS and CSS file using webpack.
I'm not much experienced with webpack and find it really difficult it wrap my hear around it. There're are a few simple questions:
1- Is this configuration correct? If yes, then how can I include my CSS and JS files in components using ES6. Something like import keyword.
2- Should I even be using webpack for CSS files?
3- How to specify individual directories for input and their respective output files in webpack? Something like all-custom.js should be output for custom1.js and custom2.js?
I know these are some very basic question and I tried Google but didn't find a single tutorial for Webpack that is simple and targets beginners.
After playing out with Webpack in multiple projects, I figured out how Webpack loads stuff. Since the question is still unanswered, I decided to do it myself for anybody with same need.
Directory structure
->assets
->css
->my-style-1.css //custom styling file 1
->my-style-2.css //custom styling file 2
->src
->app
->app.js
->variables.js
->libs.js //require all js libraries here
->styles-custom.js //require all custom css files here
->styles-libs.js //require all style libraries here
->node_modules
->index.html
->package.json
->webpack.config.js
Bundle 1 (main code of app)
app.js: assuming this is main file and app starts from here
var msgs = require('./variables');
//similarly import other js files you need in this bundle
//your application code here...
document.getElementById('heading').innerText = msgs.foo;
document.getElementById('sub-heading').innerText = msgs.bar;
Bundle 2 (js modules)
libs.js: this file will require all modules needed
require('bootstrap');
//similarly import other js libraries you need in this bundle
Bundle 3 (external css files)
styles-libs.js: this file will require all external css files
require('bootstrap/dist/css/bootstrap.css');
//similarly import other css libraries you need in this bundle
Bundle 4 (custom css files)
styles-custom.js: this file will require all custom css files
require('../assets/css/my-style-1.css');
require('../assets/css/my-style-2.css');
//similarly import other css files you need in this bundle
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const extractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'app': './src/app/app.js', //specifying bundle with custom js files
'libs': './src/libs.js', //specifying bundle with js libraries
'styles-custom': './src/styles-custom.js', //specifying bundle with custom css files
'styles-libs': './src/styles-libs.js', //specifying bundle with css libraries
},
module: {
loaders: [
//used for loading css files
{
test: /\.css$/,
loader: extractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
},
//used for loading fonts and images
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
}
]
},
output: {
path: path.resolve(__dirname, 'dist'), //directory for output files
filename: '[name].js' //using [name] will create a bundle with same file name as source
},
plugins: [
new extractTextPlugin('[name].css'), //is used for generating css file bundles
//use this for adding jquery
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jQuery'
})
]
}
index.html
<head>
<link rel="stylesheet" href="dist/styles-libs.css" />
<link rel="stylesheet" href="dist/styles-custom.css" />
</head>
<body>
<h2 id="heading"></h2>
<h3>
<label id="sub-heading" class="label label-info"></label>
</h3>
<script src="dist/libs.js"></script>
<script src="dist/app.js"></script>
</body>
You can include css & JS files using import in es6 in the source files in your project. example:
import './style.css';
import Style from './path/style.js';
NB. Generally You need to code in es5 in webpack.config.js file. If you want to use es6 just follow the link How can I use ES6 in webpack.config.js?
You can use https://github.com/webpack/css-loader for CSS configuration.
You can use code splitting in webpack and specify multiple entry point but that will generate multiple output files. Have a look at multiple entry point section of that following link.
https://webpack.github.io/docs/code-splitting.html
TL;DR: I'm getting build files that are way too big. I want them to be small and use the React source files from a CDN.
My Gulp file contains this:
gulp.task('build', () => {
browserify({
entries: dirs.src + '/index.jsx',
extensions: ['.jsx'],
debug: false
})
.transform(babelify.configure({
presets: ["es2015", "react"]
}))
.bundle()
.pipe(source('index.js'))
.pipe(gulp.dest(dirs.dest));
});
And said index.jsx file contains:
import { Provider } from 'react-redux';
import slides from './stores/slides';
const store = slides();
ReactDOM.render(
<Provider store={store}>
<h1>Test</h1>
</Provider>,
document.getElementById('target')
);
React Redux is pretty small. And if I remove that part from the latter file the result is a mere 1 KB in size. Otherwise it'll turn into 700Kb+.
I already removed these two lines from that file:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
Because I wanted to load React and ReactDOM from a CDN. Why are my files still this incredibly large?
You're currently using the development version of React. You have to build your own production version, for that the process.env.NODE_ENV flag has to be set to production.
If you're using browserify, you need envify: https://github.com/hughsk/envify
npm install envify --save-dev
Your Gulpfile.js
var envify = require('envify/custom');
//...
.transform(babelify.configure({
presets: ["es2015", "react"]
}))
.transform(envify({
NODE_ENV: 'production'
}))
//...
More resources: http://dev.topheman.com/make-your-react-production-minified-version-with-webpack/
I'm loading Ready through script tags from a CDN. I don't want to have the entire React codebase in my own local project files.
In this case, your production Webpack config should specify React in externals config option:
{
// ...
externals: {
"react": "React",
"react-dom": "ReactDOM"
},
// ...
}
Otherwise Webpack will bundle it.
Also verify that you don’t have a devtool option in the production config. It can bloat the code immensely if you use 'eval' or even inline sourcemaps.
I know uglify, but I don't want my code uglified
You should be using uglify for your code in production. This is the only way to have small builds.