Can not export webpack.config when modules:false - reactjs

Inside my index.js I am using webpack-dev-middleware/webpack-hot-middleware where I require my webpack.config and use it for compiler.
index.js
const webpack = require('webpack')
const webpackConfig = require('../../webpack.config.js')
const compiler = webpack(webpackConfig)
const webpackDevMiddleware = require('webpack-dev-middleware')
app.use(webpackDevMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath,
hot: true,
noInfo: true,
stats: {
colors: true
}
}))
app.use(require('webpack-hot-middleware')(compiler))
I try to export my webpack.config using Common.js by require and module.exports but I get error
TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
webpack.config
'use strict'
const path = require('path')
const webpack = require('webpack')
const publicPath = path.resolve(__dirname, './src/client')
const buildPath = path.resolve(__dirname, './src')
process.noDeprecation = true
module.exports = {
devtool: 'source-maps',
performance: {
hints: false
},
context: publicPath,
entry: {
bundle: [
'react-hot-loader/patch',
'webpack-hot-middleware/client?reload=false&noInfo=true',
'script-loader!jquery/dist/jquery.min.js',
'script-loader!tether/dist/js/tether.min.js',
'script-loader!bootstrap/dist/js/bootstrap.min.js',
'./app.js'
]
},
output: {
path: path.join(buildPath, 'dist'),
filename: '[name].js',
publicPath: '/'
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
CountdownForm: path.resolve(__dirname, 'src/client/scenes/countdown/components/CountdownForm.jsx'),
Countdown: path.resolve(__dirname, 'src/client/scenes/countdown/index.jsx'),
..
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules|dist|build/,
loader: 'babel-loader',
options: {
plugins: [
[
'babel-plugin-react-css-modules',
{
context: publicPath,
filetypes: {
'.scss': 'postcss-scss'
}
}
]
]
}
},
{
test: /\.local\.(css|scss)$/,
use: [
'style-loader',
'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
'postcss-loader',
'sass-loader',
{
loader: 'sass-resources-loader',
options: {
resources: path.resolve(__dirname, './src/client/styles/global/sass-resources.scss')
}
}
]
},
{
test: /^((?!\.local).)+\.(css|scss)$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery'
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development')
}
})
]
}
If I use ES6 (I am using babel and this usually works) using import statements at the top instead of require and export default instead of module.exports I get this error
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration misses the property 'entry'.
All of this is because of modules:false inside my .babelrc If I remove that Common.js way works, but I need this. How can I export webpack.config to compiler using modules:false
{
"presets": [
"react",
["es2015", { "modules": false }],
"stage-0"
],
"plugins": [
"react-hot-loader/babel",
"transform-runtime"
]
}

transform-runtime adds import and that results in mixing import with your module.exports.
Simple fix would be to replace module.exports with es6 export
module.exports = { ...webpackconfig }
becomes
export default { ...webpackconfig }
and update your index.js to use default export
const webpackConfig = require('../../webpack.config.js').default
You can find more information about this on these issues
https://github.com/webpack/webpack/issues/4039
https://github.com/webpack/webpack/issues/3917

Related

Webpack 5: Is it possible to output a javascript file non-bundled for configuration

I have a React TypeScript project that uses webpack 5.
I am trying to get a runtime-config.js file that I can change out in production by importing it as decribed in a similar Vuejs Docker issue.
I wanted to use File Loader but found that it's been deprecated in webpack 5
Here's what I want to achieve:
have ./runtime-config.js non bundled so that I can refer to it on the window object
easily reference that file in React (TypeScript) so that this dynamic configuration can be read.
Any help is appreciated.
Below is my webpack configuration:
// webpack.config.js
import path from 'path'
import { Configuration as WebpackConfiguration, DefinePlugin, NormalModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
target: 'web',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
liveReload: true,
},
output: {
publicPath: '/',
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
},
entry: {
main: './src/index.tsx',
'pdf.worker': path.join(__dirname, '../node_modules/pdfjs-dist/build/pdf.worker.js'),
},
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
{
test: /runtime-config.js$/,
use: [
{
loader: 'file-loader',
options: {
name: 'runtime-config.js',
},
},
],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new NormalModuleReplacementPlugin(
/^pdfjs-dist$/,
(resource) => {
// eslint-disable-next-line no-param-reassign
resource.request = path.join(__dirname, '../node_modules/pdfjs-dist/webpack.js')
},
),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Environment Variable for Build Number - Done in NPM scripts
new DefinePlugin({
VERSION_NUMBER: JSON.stringify(process.env.VERSION_NUMBER || 'development'),
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config

React froala Super expression must either be null or a function not undefined

I am trying to use froala editor in my react code and It is working perfectly in my local. But in production it is crashing. It is just a blank page. When I opened console there is a error message Super expression must either be null or a function not undefined. If I remove froala editor then it is working fine.
import React from 'react';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import FroalaEditorComponent from 'react-froala-wysiwyg';
const Editor = (props) => {
return <FroalaEditorComponent {...props} />;
};
export default Editor;
and this is my webpack config
const webpack = require('webpack');
const path = require('path');
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
mode: 'production',
entry: {
main: ['./client/app/main'],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM'
},
output: {
path: path.resolve(__dirname, './client/dist'),
filename: '[name].app.bundle.js',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.html$/,
loader: 'file-loader?name=[name].[ext]',
},
{
test: /\.js?$/,
exclude: /node_modules[\/\\](?!(swiper|dom7|#jimp\/core|d3-array|d3-scale|file-type|react-wordcloud|striptags)[\/\\])/,
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: ['#babel/preset-env', '#babel/react'],
plugins: [
['#babel/plugin-proposal-decorators', { 'legacy': true }],
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-class-properties',
]
},
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
],
},
resolve: {
modules: [path.resolve(__dirname, './client/app'), 'node_modules'],
extensions: ['.jsx', '.js', '.json'],
// These extensions are tried when resolving a file
enforceExtension: false,
// If false it will also try to use no extension from above
moduleExtensions: ['-loader'],
// These extensions are tried when resolving a module
enforceModuleExtension: false,
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new CompressionPlugin({
test: /\.js?$/,
deleteOriginalAssets: true,
})
],
node: {
fs: 'empty'
}
};
Any help would be really thankfull

Webpack generating [hash].worker.js file when packaging custom library

I'm trying to create a library of reusable react components for our internal use.
Webpack is bundling the output - which should be a single file. But it's actually putting out the bundle.js that I'd expect plus a file called [some_hash].worker.js.
I'm not sure how to force webpack to include that "worker" file with the single bundle that I'm asking it for.
The webpack.config:
const path = require('path');
const webpack = require('webpack');
const DIST_PATH = path.resolve(__dirname, "../dist");
const SRC_PATH = path.resolve(__dirname, "../src");
const APP_PATH = path.resolve(__dirname, "../src/index.js");
const BASE_PATH = path.resolve(__dirname);
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = ({ appPath = APP_PATH, distPath = DIST_PATH }) => ({
context: BASE_PATH,
devServer: {
contentBase: distPath,
compress: true,
port: 9000,
historyApiFallback: true
},
resolve: {
modules: ['node_modules', SRC_PATH],
alias: {
'react': path.resolve(__dirname, '../node_modules/react'),
'react-dom': path.resolve(__dirname, '../node_modules/react-dom'),
}
},
externals: {
// Don't bundle react or react-dom
react: {
commonjs: "react",
commonjs2: "react",
amd: "React",
root: "React"
},
"react-dom": {
commonjs: "react-dom",
commonjs2: "react-dom",
amd: "ReactDOM",
root: "ReactDOM"
}
},
entry: {
bundle: appPath,
},
output: {
path: distPath,
filename: 'index.js',
publicPath: '/dist/',
library: 'internal-components',
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /\.jsx$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: [
'#babel/plugin-proposal-object-rest-spread',
'#babel/plugin-syntax-dynamic-import',
[ '#babel/plugin-proposal-decorators', { 'legacy': true } ],
[ '#babel/plugin-proposal-class-properties', { 'loose': true } ]
]
}
}
},
{
test: /\.js$/,
exclude: /(node_modules|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [
'#babel/plugin-proposal-object-rest-spread',
'#babel/plugin-syntax-dynamic-import',
['#babel/plugin-proposal-decorators', {'legacy': true}],
["#babel/plugin-proposal-class-properties", {'loose': true}]
]
}
}
},
...
]
},
plugins: [
new CleanWebpackPlugin(),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
})
]
});
You might try using the worker-loader plugin with inline to handle the bundling -
rules: [
...
{
test: /\.worker\.js$/,
use: {
loader: 'worker-loader',
options: { inline: true, fallback: false }
}
}
]
That said, there are several open issues on Github surrounding using the worker as a blob, so YMMV
Actually if you are using webpack 3 and above, chunking of the bundle is automatically done for you. In the SplitChunks Plugin documentation here it is actually stated how this behaves.
So because of this you might need to scan your code and check for this conditions. Also it's good to know if you are asynchrously importing the some module? That might signal webpack to make it into a separate chunk.

material-ui.dropzone: You may need an appropriate loader to handle this file type

Integrating material-ui-dropzone in my React app, I got this error:
./~/material-ui-dropzone/src/index.jsx Module parse failed:
...\client\node_modules\material-ui-dropzone\src\index.jsx Unexpected
token (123:26) You may need an appropriate loader to handle this file
type. SyntaxError: Unexpected token (123:26)
Here is my webpack configuration:
const Path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const Webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = (options) => { const ExtractSASS = new ExtractTextPlugin(`/styles/${options.cssFileName}`);
const webpackConfig = {
devtool: options.devtool,
entry: [
`webpack-dev-server/client?http://localhost:${+ options.port}`,
'webpack/hot/dev-server',
Path.join(__dirname, '../src/app/index'),
],
output: {
path: Path.join(__dirname, '../dist'),
filename: `/scripts/${options.jsFileName}`,
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
module: {
loaders: [{
test: /.jsx?$/,
include: Path.join(__dirname, '../src/app'),
loader: 'babel',
}],
},
plugins: [
new Webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development'),
},
"global.GENTLY": false
}),
new HtmlWebpackPlugin({
template: Path.join(__dirname, '../src/index.html'),
}),
],
node: {
__dirname: true,
},
};
if (options.isProduction) {
webpackConfig.entry = [Path.join(__dirname, '../src/app/index')];
webpackConfig.plugins.push(
new Webpack.optimize.OccurenceOrderPlugin(),
new Webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false,
},
}),
ExtractSASS
);
webpackConfig.module.loaders.push({
test: /\.scss$/,
loader: ExtractSASS.extract(['css', 'sass']),
}); } else {
webpackConfig.plugins.push(
new Webpack.HotModuleReplacementPlugin()
);
webpackConfig.module.loaders.push({
test: /\.scss$/,
loaders: ['style', 'css', 'sass'],
});
webpackConfig.devServer = {
contentBase: Path.join(__dirname, '../'),
hot: true,
port: options.port,
inline: true,
progress: true,
historyApiFallback: true,
stats: 'errors-only',
}; }
return webpackConfig;
};
Babel config file is:
{
"presets": ["react", "es2015", "stage-1"]
}
It is the only library I had problems with. Any idea where might be the problem?
if you are using webapck#3.x
Try to modify your babel loader to
module: {
rules: [
{
test: /\.jsx?$/,
include: Path.join(__dirname, '../src/app'),
use: {
loader: 'babel-loader',
options: {
presets: ["react", "es2015", "stage-1"],
}
}
}
]
}
You can reference here https://webpack.js.org/loaders/babel-loader/
Noted that in your loader config, write babel-loader instead of just babel. Also make sure if you have npm install the right babel npm packages to the devDependencies, which depends on your webpack version.
If it does not solve your problem, paste your package.json file so i can get to know your webpack version.
Cheers.

Webpack build issue with mobx and mobx-react

I have a project that uses React and Mobx with Mobx-react.
My project runs perfectly fine locally. However, when built using webpack -p, I get a blank screen with the following error in the console:
webpack:///./~/mobx-react/index.js?:3 Uncaught Error: Cannot find module "mobx"
at webpackMissingModule (webpack:///./~/mobx-react/index.js?:3)
at webpackUniversalModuleDefinition (webpack:///./~/mobx-react/index.js?:3)
at eval (webpack:///./~/mobx-react/index.js?:10)
at Object.<anonymous> (bundle.js:18)
at n (bundle.js:1)
at eval (webpack:///./src/components/Category.jsx?:35)
at Object.<anonymous> (bundle.js:27)
at n (bundle.js:1)
at eval (webpack:///./src/components/CategoryNavsDates.jsx?:15)
at Object.<anonymous> (bundle.js:14)
Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer')
var CopyWebpackPlugin = require('copy-webpack-plugin');
var BUILD_DIR = path.resolve(__dirname, 'build/');
var SOURCE_DIR = path.resolve(__dirname, 'src/');
module.exports = {
devtool: 'eval',
entry: SOURCE_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
plugins: ['transform-decorators-legacy'],
presets: ['es2015', 'stage-0', 'react']
}
},
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: "[name]__[local]___[hash:base64:3] "} },
{ loader: 'postcss-loader', options: {} },
]
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
postcss: function () {
return [
require('postcss-import'),
require('postcss-cssnext'),
];
},
}
}),
new CopyWebpackPlugin([{ from: 'index.html', to: '' },])
],
devServer: {
historyApiFallback: true
},
};
There is only one file using Mobx in my entire project, and that is the file the error refers to, Category.jsx.
Category.jsx sample:
import { observer } from 'mobx-react'
import { observable } from 'mobx'
...
#observer class Category extends React.Component {
#observable showingSmallMenu = false
...
}
As I say this all works perfectly fine locally.
What could be the problem here?
Does it make a difference if you import mobx before mobx-react?
In my case, that is caused by:
alias: {
mobx: __dirname + '/node_modules/mobx/lib/mobx.es6.js'
}
Remove mobx alias, then the problem is solved

Resources