I'm having a little bit of an issue when I want to implement auth0 on my project.
Whenever I solve one problem I run into another, it's always the same 3 errors :
-require is not a function
-window is not defined
-missing class properties
I've tried solving it by playing with the babelrc, changing the order of the presets
And in webpack I've added the famous as below:
"plugins: [new webpack.DefinePlugin({ 'global.GENTLY': false })],"
in webpack to no avail
I'm providing the package json/ babelrc & web pack without the modifications I cited above so you can see the "base" without the failed attempts at fixing it
Also providing the screenshots with the errors
Thanks in advance
https://imgur.com/a/8TT3v44
for the errors
this is in babelrc
{
"presets": [
"#babel/preset-react",
["#babel/preset-env", { "modules": false }],
["#babel/preset-stage-0", { "decoratorsLegacy": true }]
],
"env": {
"development": {
"compact": false
},
"jest": {
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
},
"plugins": [
"#babel/plugin-proposal-export-default-from",
[
"react-intl",
{
"messagesDir": "./extracted_messages/",
"enforceDescriptions": true
}
]
]
}
and this is the webpack
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const distDir = path.join(__dirname, '../dist')
const srcDir = path.join(__dirname, '../src')
module.exports = [
{
name: 'client',
target: 'web',
mode: 'development',
entry: `${srcDir}/client.jsx`,
output: {
path: distDir,
filename: 'client.js',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.join(__dirname, '../config'),
utils: path.join(__dirname, '../src/utils'),
toolbox: path.join(__dirname, '../src/components/toolbox')
}
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules\/)/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
query: { name: 'assets/images/[name].[ext]' }
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: 'file-loader',
query: { name: 'assets/fonts/[name].[ext]' }
}
]
},
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new MiniCssExtractPlugin({
filename: 'styles.css'
}),
new CopyPlugin([{ from: `${srcDir}/favicon.ico`, to: distDir }])]
},
{
name: 'server',
target: 'node',
mode: 'development',
entry: `${srcDir}/server.jsx`,
output: {
path: distDir,
filename: 'server.js',
libraryTarget: 'commonjs2',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.join(__dirname, '../config'),
utils: path.join(__dirname, '../src/utils'),
toolbox: path.join(__dirname, '../src/components/toolbox'),
inherits: 'inherits/inherits_browser.js',
superagent: 'superagent/lib/client',
emitter: 'component-emitter',
}
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules\/)/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
{
loader: 'isomorphic-style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
query: { name: 'assets/images/[name].[ext]' }
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: 'file-loader',
query: { name: 'assets/fonts/[name].[ext]' }
}
]
},
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new CopyPlugin([{ from: `${srcDir}/favicon.ico`, to: distDir }])]
}
]
I ran into this problem while writing for our blog. Our suggested fix is this;
function whatYouRunOnPageLoad() {
if (typeof window !== undefined) {
auth0.parseHash(... etc ...)
}
}
parseHash requires window, which does not exist as part of your render steps. Auth0.js cannot run from serverside, which is what is "accidentally" happening when you try to render it the way you are.
Window error solved by doing:
if(global.window){...}
and later on by just not calling the function I was using at inappropriate times.
Require is not a function solved with:
[new webpack.DefinePlugin({ 'global.GENTLY': false })]
in the webpack config at plugins (dev AND prod, idk why) + importing it with require and not import.
Webpack module error solved by changing the order of the presets in bablerc.
Related
I have setup a simple webpack 5 config file with a dev server that seems to be working but when I add
<link href="/style.css" rel="stylesheet" />
to the index.html file I get no CSS loading. Currently in dev mode I am choosing to use 'style-loader' over the 'MiniCssExtractPlugin' to enable hot module reloading natively.
any help would be greatly appreciated. There are no errors in the webpack console output just no CSS to call from the HTML file.
Webpack file:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = (env, options) => {
const mode = options.mode;
return {
context: __dirname,
entry: {
script: './src/index.bundle.ts',
style: './src/index.bundle.less',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './src/dist')
},
devServer: {
watchFiles: ['src/**/*.less'],
static: {
directory: path.join(__dirname, 'src'),
watch: true,
},
compress: true,
port: 9000,
hot: true,
},
devtool: 'source-map',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.css', '.less']
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
ignoreOrder: false,
}),
],
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
target: 'browserslist'
}
}
},
{
test: /\.ts(x)?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
mode === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
{
loader: 'css-loader',
},
{
loader: 'postcss-loader', // Run postcss actions
options: {
postcssOptions: {
config: path.resolve(__dirname, "postcss.config.js"),
}
}
},
]
},
{
test: /\.less$/,
use: [
mode === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
'css-loader',
'less-loader'
]
},
]
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin(), new CssMinimizerPlugin()]
},
target: 'web',
}
};
It appears you've misconfigured
static: {
directory: path.join(__dirname, 'src'),
Your output points to src/dist so it looks like it should be this instead
static: {
directory: path.join(__dirname, 'src/dist'),
On a side note, it's an anti-pattern to have compiled files within your source folder. Generally this structure is recommended.
[repo_root]/
dist/
src/
I have an Angular 12 application that is bundled with Webpack 5. I recently noticed that images that are specified in HTML file component templates are not copied to the output 'dist' folder when running a production build. However, when a development build is run, the files are copied correctly into the 'dist' folder. Below are the Webpack configuration files that are used. The webpack-common.js file is shared by both builds. The webpack-dev.js and webpack-prod.js files are used for development and production respectively. The webpack-merge plugin is used to merge each with the webpack-common.js.
For example, lets say I add an image to my app.component.html file as follows:
<img class="my-image" src="./assets/images/my-image.png" />
In the development build, I will see the image in 'dist/assets/my-image.png', However, the image never makes it there in the production build.
When I observe the Network traffic in the Chrome DevTools using the development build, I see the network Request URL for the image correctly as: localhost/dist/assets/my-image.png. However, in the production build, I see the Request URL as: localhost/app/assets/images/my-image.png, which is the original location of the file in the project folder.
What am I missing from the Webpack configuration to correct this problem for production builds?
webpack-common.js
module.exports = {
output:
{
filename: '[name].js',
chunkFilename: '[name].js',
publicPath: './dist/',
path: path.resolve(__dirname, 'dist'),
assetModuleFilename: 'assets/[hash][ext][query]'
}
,
module: {
rules: [
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
{
loader: 'css-to-string-loader'
},
{
loader: 'css-loader'
},
{
loader: 'fast-sass-loader',
options:
{
implementation: require('node-sass')
}
}
]
},
{
test: /\.html$/,
use: 'html-loader'
},
{
test: /\.(eot|woff|woff2|ttf|png|jpg|gif|svg|ico)$/,
type: 'asset/resource'
}
]
},
resolve: {
extensions: ['.ts', '.js'],
mainFields: ['es2015', 'browser', 'module', 'main'],
},
plugins: [
new CleanWebpackPlugin(),
],
optimization:
{
minimizer: [new TerserPlugin({
extractComments: false,
})],
splitChunks: {
cacheGroups:
{
commons:
{
test: /[\\/](node_modules)[\\/]/,
name: 'vendors',
chunks: 'all',
}
}
}
}
};
webpack-dev.js
module.exports = merge(common,
{
mode: 'development',
devtool: 'eval-cheap-module-source-map',
entry:
{
appbundle: './app/main.ts'
},
module:
{
rules:
[
{
test: /\.tsx?$/,
use: [
{
loader: 'cache-loader'
},
{
loader: 'happypack/loader'
},
{
loader: 'angular-router-loader'
},
{
loader: 'angular2-template-loader?keepUrl=false'
}
],
include: [path.resolve(__dirname, "app")],
exclude: [path.resolve(__dirname, "node_modules")]
}
]
},
plugins:
[
new webpack.ContextReplacementPlugin(/\#angular(\\|\/)core(\\|\/)esm5/, path.join(__dirname, './app')),
new ForkTsCheckerWebpackPlugin({
typescript: {
memoryLimit: 4096,
mode: 'write-tsbuildinfo'
}
}),
new HappyPackPlugin({
threads: 4,
loaders:
[
{
loader: 'ts-loader',
options: { transpileOnly: true, happyPackMode: true }
}
]
})
]
});
webpack-prod.js
module.exports = merge(common,
{
mode: 'production',
entry:
{
appbundle: './app/main-prod.ts'
},
module:
{
rules:
[
{
test: /\.[jt]sx?$/,
use: '#ngtools/webpack',
include: [path.resolve(__dirname, "app")],
exclude: [path.resolve(__dirname, "node_modules")]
}
]
},
plugins:
[
new AngularWebpackPlugin({
tsconfig: './tsconfig.json'
})
]
});
I am setting up a webpack, but I have a problem.
I know that libraries are automatically connected when node_modules is set in modules of resolve.
So I set up the webpack like this(the webpack file is located under the config folder in the root folder.)
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const env = process.env.NODE_ENV;
const isProd = env === "production";
module.exports = {
mode: env,
context: path.resolve(__dirname, '..'),
entry: {
app: './main.js'
},
output: {
filename: !isProd ? `js/[name].js` : 'js/[name].[contenthash:8].js',
path: path.resolve(__dirname, '../dist'),
publicPath: '/',
chunkFilename: !isProd ? `js/[name].js` : 'js/[name].[contenthash:8].js'
},
resolve: {
alias: {
'#': path.resolve(__dirname, '../src'),
vue$: 'vue/dist/vue.runtime.esm-bundler.js'
},
extensions: [
'.mjs',
'.js',
'.jsx',
'.vue',
'.json',
],
modules: [
path.resolve(__dirname, '../src'),
'node_modules',
path.resolve(__dirname, '../node_modules')
],
},
resolveLoader: {
modules: [
'node_modules',
path.resolve(__dirname, '../node_modules')
],
extensions: ['.js', '.json'],
},
module: {
noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/,
rules: [
{
test: /\.vue$/,
use: ['vue-loader']
},
{
test: /\.(png|jpe?g|gif|webp)(\?.*)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 4096,
fallback: {
loader: 'file-loader',
options: {
name: 'img/[name].[hash:8].[ext]',
esModule: false
}
}
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
use: [ isProd ? {
loader: MiniCssExtractPlugin.loader
} : {
loader: 'style-loader',
}
,
{
loader: "css-loader",
options: {
sourceMap: false,
importLoaders: 2
}
},
{
loader: "sass-loader",
options: {
sourceMap: false
}
}],
},
{
enforce: 'pre',
test: /\.(vue|(j|t)sx?)$/,
exclude: [
/node_modules/,
],
use: [
{
loader: 'eslint-loader',
options: {
extensions: [
'.js',
'.jsx',
'.vue'
],
emitWarning: false,
emitError: false,
fix: true,
}
}
]
},
{
test: /\.m?jsx?$/,
use: [
{loader: 'babel-loader'}
]
}
],
},
plugins: [
new VueLoaderPlugin(),
],
}
However, despite of this setting, code cannot find node_modules.
import Vue from 'vue';
import App from "./src/App.vue";
import { router } from "./src/router/index.js";
new Vue({
router,
render: (h) => h(App),
}).$mount("#root");
this prints out error message on the dev server or at build time.
ERROR in ./main.js
Module not found: Error: Can't resolve 'vue' in '/Users/donghokim/study/wecode/vue-setting-playground/brandi-front-setting'
# ./main.js 1:0-22 5:4-7
However, if set the library path directly, it works.
import Vue from './node_modules/vue/dist/vue';
import App from "./src/App.vue";
import { router } from "./src/router/index.js";
new Vue({
router,
render: (h) => h(App),
}).$mount("#root");
How can I automatically connect node_modules?
solved.... vue$: 'vue/dist/vue.runtime.esm-bundler.js' is of vue 3. I found that vue 2 has no vue.runtime.esm-bundler.js file. After changing to vue.runtime.esm.js, webpack build works
i want to build 1 nodejs app. I do not understand why when I build a version and copy to another place and run the node can not run because of the lack of modules.
this is file webpack:
const nodeExternals = require('webpack-node-externals')
const fs = require('fs')
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function (x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function (mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
mode: 'development',
target: "node",
entry: {
server: './src/index.js',
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js',
},
node: {
__gloabal: true,
__filename: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: '/node_modules',
use: {
loader: "babel-loader"
}
},
{
test: /\.json$/,
loader: "json"
}
]
},
resolve: {
extensions: [".js", ".json"],
},
externals: [nodeModules],
optimization: {
minimize: true
}
}
and here when i'm running in folder before coppy:
Because you use Externals configuration option
The externals configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's (any end-user application) environment. This feature is typically most useful to library developers, however there are a variety of applications for it.
module.exports = {
mode: 'development',
target: 'node',
entry: {
server: './src/index.js'
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
node: {
__gloabal: true,
__filename: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: '/node_modules',
use: {
loader: 'babel-loader'
}
},
{
test: /\.json$/,
loader: 'json'
}
]
},
resolve: {
extensions: ['.js', '.json']
},
optimization: {
minimize: true
}
};
I tried to use winston dependency in a cordova application. I know that cordova doesn't have fs module so I don't use file transport from winston. But I found that the build failed with below error:
Module not found: Error: Can't resolve 'fs' in '/ui/node_modules/winston/lib/winston/transports'
# /Users/joeyzhao/dev/mpost/ap-ui/~/winston/lib/winston/transports/file.js 10:11-24
# /Users/joeyzhao/dev/mpost/ap-ui/~/winston/lib/winston/transports/index.js
# /Users/joeyzhao/dev/mpost/ap-ui/~/winston/lib/winston.js
I know that winston doesn't support browser yet. But what I try to understand is whether winston core has fs dependency. It helps me to estimate how much work I should spend on to make winston to work with browser.
Below is how I use winston.
import { createLogger, format, transports } from "winston";
export const defaultTransports = {
console: new transports.Console()
};
export const logger = createLogger({
transports: [defaultTransports.console],
format: format.combine(
format.timestamp(),
exitOnError: false,
exceptionHandlers: [defaultTransports.console],
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug'
});
I am using webpack to build the code and below is the config:
config: {
devtool: isProd ? false : 'eval-source-map',
context: sourcePath,
target: 'web',
watchOptions: {
ignored: [/mobile/, /build/, /coverage/]
},
entry: ['./index.tsx'],
output: {
filename: 'bundle.js'
},
module: {
rules: [
{
test: /^(?!.*\.generated\.ttf$).*\.ttf$/,
use: ['css-loader', 'fontface-loader']
},
{
test: /\.generated.(ttf|eot|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {
name: './assets/fonts/[name].[ext]'
}
}
]
},
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
plugins: ['#extjs/reactor-babel-plugin']
}
},
{
loader: 'awesome-typescript-loader'
}
]
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: './assets/images/[name].[ext]'
}
},
{
loader: 'image-webpack-loader'
}
]
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
camelCase: true
}
}
]
}
]
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
alias: {
'#ap-components': path.join(__dirname, 'src', 'components'),
'#ap-contexts': path.join(__dirname, 'src', 'contexts'),
'#ap-modules': path.join(__dirname, 'src', 'modules'),
'#ap-views': path.join(__dirname, 'src', 'views'),
}
},
plugins,
stats: {
colors: {
green: '\u001b[32m'
}
}
}
};