I can't deal with SSR React - javascript

When I import the react component for the next SSR, it gives an import error, what could be the matter? I don't want to use type module in package.json
Maybe I made a mistake somewhere.....I will be very grateful for your help
babel.rc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
"#babel/register"
]
}
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { getGlobals } = require("./config/get-globals");
const isDev = process.env.NODE_ENV === "development";
const isProd = !isDev;
const globals = getGlobals();
const optimization = () => {
const config = {
splitChunks: {
chunks: "all",
},
};
if (isProd) {
config.minimizer = [
new CssMinimizerWebpackPlugin(),
new TerserWebpackPlugin(),
];
}
return config;
};
const ClientConfig = {
entry: path.join(__dirname, "src", "index.jsx"),
output: {
path: path.join(__dirname, "build"),
filename: "[name].[contenthash].js",
},
mode: 'development' === process.env.NODE_ENV ? 'development' : 'production',
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "public", "index_template.ejs"),
favicon: "src/public/favicon.ico",
alwaysWriteToDisk: true,
minify: {
collapseWhitespace: isProd,
},
inject: false,
templateParameters: (options) => {
const js = Object.keys(options.assets)
.filter((el) => /\.js$/.test(el))
.map((el) => "/" + el);
const css = Object.keys(options.assets)
.filter((el) => /\.css$/.test(el))
.map((el) => "/" + el);
return {
css,
js,
globals,
};
},
}),
new HtmlWebpackPlugin({
inject: false,
minify: false,
template: path.resolve(__dirname, "config", "render-stats.js"),
filename: path.join(__dirname, "config", "build-stats.json"),
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
}),
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, "src", "public", "favicon.ico"),
to: path.resolve(__dirname, "build"),
},
],
}),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: "ts-loader",
},
},
{
test: /\.(png|svg|jpg|gif|jpeg|ico)$/,
use: ["file-loader"],
},
{
test: /\.(ttf|woff|woff2|eot)$/,
use: ["file-loader"],
},
{
test: /\.xml$/,
use: ["xml-loader"],
},
{
test: /\.csv$/,
use: ["csv-loader"],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: 1,
modules: true,
},
},
],
},
{
test: /\.ejs$/,
use: { loader: "ejs-compiled-loader", options: {} },
},
],
},
resolve: {
extensions: [".js", ".jsx", ".ejs", ".tsx", ".ts"],
},
devServer: {
port: 3007,
hot: isDev,
},
optimization: optimization(),
};
module.exports = [ClientConfig];
server.js
const express = require("express");
const fs = require("fs");
const path = require("path");
// create express application
const app = express();
// import App component
const { App } = require("../src/components/app.tsx");
app.use("*", (req, res) => {
let indexHTML = fs.readFileSync(path.resolve(__dirname, "../build/index.html"), {
encoding: "utf8"
});
// set header and status
res.contentType("text/html");
res.status(200);
return res.send(indexHTML);
});
// run express server on port 9000
app.listen("9000", () => {
console.log("Express server started at http://localhost:9000");
});
Error
import * as React from "react";
^^^^^^
SyntaxError: Cannot use import statement outside a module

Use this configuration for compile server filewebpack.server.config.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/server/index.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, './dist/server'),
filename: 'server.js'
},
resolve : {
extensions : [".js",".jsx"],
},
module: {
rules: [
{
test: /\.jsx?/,
use: 'babel-loader'
}
]
}
};

Related

How to run build two react projects together

**I have two single-spa projects (root-config, app-hello) and I need to create a build so that the file name is the same in both root-config and app-hello. The problem is that when I run the proteins separately in the build I get different dates in the file name and for this I am looking for a way to build them together **
Webpack app-hello
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const Dotenv = require('dotenv-webpack');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
const singleSpaDefaults = require('webpack-config-single-spa-react');
const override = require('./config-overrides.js');
module.exports = (webpackConfigEnv, argv) => {
const defaultConfig = singleSpaDefaults({
orgName: 'app',
projectName: 'hello',
webpackConfigEnv,
argv,
override,
});
return merge(defaultConfig, {
resolve: {
extensions: ['.ts', '.tsx', '.js'],
preferRelative: true,
alias: {
containers: path.resolve(__dirname, 'src/containers'),
components: path.resolve(__dirname, 'src/components'),
layouts: path.resolve(__dirname, 'src/layouts'),
stores: path.resolve(__dirname, 'src/stores'),
hooks: path.join(__dirname, 'src/hooks'),
context: path.join(__dirname, 'src/context'),
assets: path.join(__dirname, 'src/assets'),
helpers: path.join(__dirname, 'src/helpers'),
},
plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.json' })],
},
devServer: {
port: 8500,
},
plugins: [
new Dotenv({
path: './.env.development',
}),
new FilterWarningsPlugin({
exclude:
/There are multiple modules with names that only differ in casing/,
}),
new CleanWebpackPlugin(),
],
output: {
path: path.resolve(__dirname, 'build'),
filename: `app-chat-${Date.now()}.js`,
assetModuleFilename: 'assets/[name][ext]',
},
module: {
rules: [
{
test: /\.m?js/,
type: 'javascript/auto',
resolve: {
fullySpecified: false,
},
},
{
test: /\.js$|jsx/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.json$/,
use: 'json-loader',
},
{
test: /\.svg$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['preact', 'env'],
},
},
{
loader: '#svgr/webpack',
options: { babel: false },
},
],
},
],
},
});
};
webpack root-config
const { merge } = require("webpack-merge");
const singleSpaDefaults = require("webpack-config-single-spa-ts");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = (webpackConfigEnv, argv) => {
const orgName = "app";
const defaultConfig = singleSpaDefaults({
orgName,
projectName: "root-config",
webpackConfigEnv,
argv,
disableHtmlGeneration: true,
});
return merge(defaultConfig, {
plugins: [
new HtmlWebpackPlugin({
inject: false,
template: "src/index.ejs",
templateParameters: {
isLocal: webpackConfigEnv && webpackConfigEnv.isLocal,
orgName,
hash: Date.now(),
},
}),
],
});
};
index root-config
<script type="systemjs-importmap">
{
"imports": {
"react": "https://cdn.jsdelivr.net/npm/react#17.0.2/umd/react.production.min.js",
"react-dom": "https://cdn.jsdelivr.net/npm/react-dom#17.0.2/umd/react-dom.production.min.js",
"single-spa": "https://cdn.jsdelivr.net/npm/single-spa#5.9.0/lib/system/single-spa.min.js",
"#app/root-config": "https://login-7mpuan0pw5.s3.amazonaws.com/app-root-config.js",
"#app/chat": "https://login-7mpuan0pw5.s3.amazonaws.com/app-chat-<%= hash %>.js",
"#app/switcher": "https://login-7mpuan0pw5.s3.amazonaws.com/switcher/app-switcher-<%= hash %>.js"
}
}
</script>

Webpack 5 SCSS and JS save returns old version of page

I work with webpack 5. Pug works well - after autosave or cmd+S I get new version of page. And it doesn't work so with JS and SCSS: SCSS autosave works well but after cmd+S I get some old version of page(usually everytime the same). With JS both autosave and cmd+S return some old version of page. Can you help me to find a solution? Below I dropped webpack.config.js
const path = require("path");
const fs = require("fs");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const isDev = process.env.NODE_ENV === "development";
const isProd = !isDev;
const PATHS = {
src: path.join(__dirname, "./src"),
dist: path.join(__dirname, "./dist"),
};
const PAGES_DIR = `${PATHS.src}/`;
const PAGES = fs.readdirSync(PAGES_DIR).filter((fileName) => fileName.endsWith(".pug"));
const filename = (ext) => `[name].${ext}`;
const plugins = () => {
const basePlugins = [
...PAGES.map(
(page) =>
new HTMLWebpackPlugin({
template: `${PAGES_DIR}/${page}`,
filename: `./${page.replace(/\.pug/, ".html")}`,
})
),
new MiniCssExtractPlugin({
filename: `./css/${filename("css")}`,
}),
new CopyWebpackPlugin({
patterns: [
{ from: path.resolve(__dirname, "src/assets"), to: path.resolve(`${PATHS.dist}`) },
{ from: path.resolve(__dirname, "src/img"), to: path.resolve(`${PATHS.dist}/img/`) },
],
}),
];
return basePlugins;
};
module.exports = {
context: path.resolve(`${PATHS.src}`),
mode: "development",
entry: "./js/main.js",
output: {
filename: `./js/${filename("js")}`,
path: path.resolve(`${PATHS.dist}`),
publicPath: "",
clean: true,
},
devServer: {
historyApiFallback: true,
static: path.resolve(`${PATHS.dist}`),
open: true,
compress: true,
hot: true,
port: 3000,
},
optimization: {
splitChunks: {
chunks: "all",
},
},
plugins: plugins(),
devtool: isProd ? false : "source-map",
module: {
rules: [
{
test: /\.pug$/,
loader: "pug-loader",
},
{
test: /\.s[ac]ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
return path.relative(path.dirname(resourcePath), context) + "/";
},
},
},
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: ["postcss-preset-env"],
},
},
},
"sass-loader",
],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.(?:|gif|png|jpg|jpeg|svg|webp)$/,
use: [
{
loader: "file-loader",
options: {
name: `./img/${filename("[ext]")}`,
},
},
],
},
{
test: /\.(?:|woff2)$/,
use: [
{
loader: "file-loader",
options: {
name: `./fonts/${filename("[ext]")}`,
},
},
],
},
],
},
};
I don't know what to write here. I described my problem above.

Webpack 5 - some styles are missing in production but exist in development

I found that some of the styles are not applied in Production website, but working in development env(localhost).
But Inspecting in Browser Inspector > Sources, I found that in Production sources(css/main.c938xxxxx.css), it missed #roadmap .slick-slide{padding:0 18px}}

Which exist in localhost

Not sure what’s wrong for the production webpack setting. I am using webpack 5
Webpack.base.js
const webpack = require("webpack");
const utils = require("./utils");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const ProgressBarPlugin = require("progress-bar-webpack-plugin");
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const chalk = require("chalk");
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
entry: "./src/index.jsx",
resolve: {
alias: {
"#": utils.resolve("src"),
},
extensions: ["*", ".js", ".jsx"],
fallback: {…},
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
}
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
},
{
loader: "sass-loader",
},
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
{
test: /\.(png|jpg|gif|svg)$/i,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: 8192
}
}
},
{
test: /\.(ico)$/,
exclude: /node_modules/,
use: ["file-loader?name=[name].[ext]"], // ?name=[name].[ext] is only necessary to preserve the original file name
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "public/index.html",
filename: "index.html",
favicon: "public/favicon.ico",
manifest: "public/manifest.json",
inject: true,
}),
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
}),
new webpack.ProvidePlugin({
process: "process/browser",
}),
new ProgressBarPlugin({
format: ` :msg [:bar] ${chalk.green.bold(":percent")} (:elapsed s)`,
}),
],
});
webpack.dev.js
const { merge } = require("webpack-merge");
const path = require("path");
const base = require("./webpack.base");
const utils = require("./utils");
const Dotenv = require("dotenv-webpack");
module.exports = merge(base, {
mode: "development",
devtool: "inline-source-map",
output: {
publicPath: '/',
assetModuleFilename: (pathData) => {
const filepath = path
.dirname(pathData.filename)
.split("/")
.slice(1)
.join("/");
return `${filepath}/[name].[hash][ext][query]`;
},
},
devServer: {
port: 3300,
static: [
{ directory: utils.resolve("dist") },
{ directory: utils.resolve("public") },
],
},
plugins: [new Dotenv({ path: "./.env.dev })],
});
webpack.uat.js
const { merge } = require("webpack-merge");
const base = require("./webpack.base");
const path = require("path");
const Dotenv = require("dotenv-webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = ["js", "css"];
module.exports = merge(base, {
mode: "production",
output: {
path: path.join(__dirname, "../dist"),
filename: "js/[name].[contenthash].js",
assetModuleFilename: (pathData) => {
const filepath = path
.dirname(pathData.filename)
.split("/")
.slice(1)
.join("/");
return `${filepath}/[name].[hash][ext][query]`;
},
},
optimization: {
minimizer: [`...`, new CssMinimizerPlugin()],
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
},
"sass-loader",
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
],
},
plugins: [
new Dotenv({ path: "./.env.uat" }),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "css/[name].[contenthash].css",
}),
new CompressionPlugin({
filename: "[path][name].gz[query]",
algorithm: "gzip",
test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"),
threshold: 10240,
minRatio: 0.8,
})
],
});
utils.js
const path = require('path')
module.exports = {
resolve: function(dir) {
return path.join(__dirname, '..', dir)
}
}
Add "style-loader" in webpack.uat.js file.
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "style-loader",
},
{
loader: "css-loader",
},
"sass-loader",
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
],

Webpack unexpected behavior TypeError: Cannot read property 'call' of undefined

Recently we have updated webpack to v4 and soon noticed unexpected errors from webpack during development, which disappears after rebuild of entire bundle.
Our application build using lazy loading and code splitting, which can cause the issue, though I couldn't find anything related to this in the official documentations.
Here the error we get
react_devtools_backend.js:2273 TypeError: Cannot read property 'call' of undefined
our webpack webpack.config.js file.
const webpack = require('webpack');
const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
// minification plugins
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// image optimization plugins
const ImageminPlugin = require("imagemin-webpack-plugin").default;
const imageminGifsicle = require("imagemin-gifsicle");
const imageminPngquant = require("imagemin-pngquant");
const imageminSvgo = require("imagemin-svgo");
const imageminMozjpeg = require('imagemin-mozjpeg');
const env = require('dotenv').config();
const isProd = process.env.NODE_ENV === 'production';
const isDev = !isProd;
const environment = {
NODE_ENV: process.env.NODE_ENV || 'development',
CONFIG: process.env.CONFIG || 'development',
DEBUG: process.env.DEBUG || false,
};
const plugins = () => {
let plugins = [
new CleanWebpackPlugin(['build', 'cachedImages'], {
root: path.resolve(__dirname, '../dist'),
verbose: true,
dry: false,
}),
new webpack.EnvironmentPlugin(Object.assign(environment, env.parsed)),
new MiniCssExtractPlugin('[chunkhash:5].[name].[hash].css'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
moment: 'moment',
_: 'lodash',
}),
new webpack.ContextReplacementPlugin(/moment[\\\/]locale$/, /^\.\/(en)$/),
new AssetsPlugin({
filename: 'assets.json',
}),
new ImageminPlugin({
cacheFolder: isDev ? path.resolve(__dirname, '../dist/cachedImages') : null,
externalImages: {
context: 'src',
sources: glob.sync('src/assets/img/**/*.*'),
destination: 'dist/img/',
fileName: (filepath) => {
let name = filepath.split(/img(\/|\\)/).pop();
return name;
},
},
plugins: [
imageminGifsicle({
interlaced: false
}),
imageminMozjpeg({
progressive: true,
arithmetic: false
}),
imageminPngquant({
floyd: 0.5,
speed: 2
}),
imageminSvgo({
plugins: [
{ removeTitle: true },
{ convertPathData: false }
]
}),
],
}),
];
if (isProd) {
plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: path.resolve(__dirname, 'analysis.html'),
generateStatsFile: false,
logLevel: 'info',
})
);
}
return plugins;
};
const optimization = () => {
let optimizations = {
concatenateModules: true,
splitChunks: {
cacheGroups: {
vendor: {
name: 'vendor',
test: /[\\/]node_modules[\\/](react|react-dom|lodash|moment)[\\/]/,
chunks: 'all',
},
commons: {
chunks: 'async',
}
}
}
};
if (isProd) {
optimizations.minimizer = [
new TerserJSPlugin({
terserOptions: {
compress: {
pure_funcs: ['console.log'],
drop_console: true,
drop_debugger: true
},
warnings: false
},
parallel: true
}),
new OptimizeCSSAssetsPlugin({})
];
}
return optimizations;
};
const fontLoaders = [
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=application/font-woff',
}
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=application/font-woff',
}
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=application/octet-stream',
}
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url?limit=10000&mimetype=image/svg+xml',
}
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'file',
}
}
];
const config = {
mode: process.env.NODE_ENV,
devtool: isDev ? 'source-map' : '',
context: path.resolve(__dirname, '../src'),
entry: {
bundle: './app.jsx',
embed: './embed.jsx',
styles: './sass_new/main.scss',
vendor: [
'react',
'react-dom',
'redux',
'redux-saga',
'react-redux',
'react-router',
'react-tap-event-plugin',
'lodash',
'moment',
]
},
output: {
publicPath: '/build/',
filename: '[name].[hash].js',
chunkFilename: '[name].[hash].js',
path: path.resolve(__dirname, '../dist/build'),
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.resolve(__dirname, '../config.js'),
utils: path.resolve(__dirname, '../src/utils'),
shared: path.resolve(__dirname, '../src/components/shared'),
services: path.resolve(__dirname, '../src/services'),
store: path.resolve(__dirname, '../src/store'),
constants: path.resolve(__dirname, '../src/constants'),
actions: path.resolve(__dirname, '../src/actions'),
components: path.resolve(__dirname, '../src/components'),
},
},
optimization: optimization(),
plugins: plugins(),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/, /libs/],
use: {
loader: path.join(__dirname, '../helpers/custom-loader.js'),
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: [
'#babel/plugin-proposal-object-rest-spread',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-destructuring',
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-transform-runtime',
'syntax-async-functions'
]
}
}
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
'sass-loader',
]
},
{
test: /\.css$/,
use: [
'css-loader'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "url-loader",
options: {
name: "[path][name].[ext]"
},
},
...fontLoaders
]
},
watchOptions: {
ignored: /node_modules/,
},
};
module.exports = config;
I have no idea how to fix this, and it's taking a lot of time to rebuild entire app after getting this error.

vendor in Webpack is disabling my CSS

entry: {
vender: [
'react',
'react-dom',
'eslint-plugin-react',
],
},
The code snippet above seems to be the cause of my issues. This code sample is a part of my webpack.config.js file. If I run yarn build for this application it removes my CSS file that was being created through the ExtractTextWebpackPlugin (ETP in my code). If I comment out the code section above the CSS file is present in the public directory after I run build. Would anyone happen to know how I can remedy this issue.
const ETP = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const parts = require('./webpack.parts');
const path = require('path');
const webpack = require('webpack');
const glob = require('glob');
const PATHS = {
public: path.join(__dirname, 'public'),
src: path.join(__dirname, 'src'),
styles: path.join(__dirname, 'src', 'scss'),
};
const options = {
host: 'localhost',
port: '8085',
};
const commonConfig = merge([
{
entry: PATHS.src,
output: {
path: PATHS.public,
filename: '[name].bundle.js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Jason Ganz Portfolio',
template: path.join(PATHS.src, 'index.html'),
}),
new OpenBrowserPlugin({
url: `http://${options.host}:${options.port}`,
}),
new ETP('style.css'),
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnWarning: false,
failOnError: true,
fix: false,
// // Output to Jenkins compatible XML
// // outputReport: {
// // filePath: 'checkstyle.xml',
// // formatter: require('eslint/lib/formatters/checkstyle'),
// // },
},
},
}),
parts.purifyCSS({
paths: glob.sync(`${PATHS.src}/**/*.js`, {nodir: true}),
}),
],
},
parts.loadSASS(PATHS.styles),
parts.loadJSX(),
]);
const productionConfig = merge([
//Generates Source Maps for js files
parts.generateSourceMaps({ type: 'source-map' }),
{
entry: {
vender: [
'react',
'react-dom',
'eslint-plugin-react',
],
},
plugins: [ new webpack.optimize.CommonsChunkPlugin({name: 'vendor'})],
},
]);
const developmentConfig = merge([
parts.devServer({
host: options.host,
port: options.port,
path: PATHS.public,
}),
{
output: {
devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]',
},
},
parts.generateSourceMaps({ type: 'cheap-module-eval-source-map' }),
]);
module.exports = (env) => {
if(env == 'development') {
return merge(commonConfig, developmentConfig);
}
return merge(commonConfig, productionConfig);
};
My loaders and modules are being stored in a separate webpack.parts.js file which can be seen below.
const ETP = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
exports.devServer = ({host, port, path} = {})=> ({
devServer: {
compress: true,
contentBase: path,
historyApiFallback: true,
host,
port,
overlay: {
errors: true,
warnings: true,
},
stats: 'errors-only',
},
});
exports.generateSourceMaps = ({ type }) => ({
devtool: type,
});
exports.loadCSS = () => ({
module:{
loaders: [{
test: /\.css$/,
loader: ['style-loader','css-loader'],
}],
},
});
exports.loadJSX = () => ({
module:{
loaders: [{
test: /\.(js|jsx)$/,
exclude: '/node_modules/',
loader: 'babel-loader',
}],
},
});
exports.loadSASS = (path) => ({
module: {
loaders: [{
test: /\.(css|sass|scss)$/,
loader: ETP.extract({
fallback: 'style-loader',
use: 'css-loader!postcss-loader!sass-loader',
}),
include: path,
}],
},
});
exports.purifyCSS = ({ paths }) => (new PurifyCSSPlugin({paths}))
You are writing "vender" instead of "vendor" in the entry property

Categories

Resources