Uncaught ReferenceError: exports is not defined after Webpack Code Split - javascript

I am trying to optimize my webpack bundle size by splitting it into two bundles: webpack-bundle.js, which contains my code, and vendor-bundle.js, which contains node modules and third party libraries. But after I successfully created two bundles, I am getting two errors in the browser regarding both bundles:
Uncaught ReferenceError: exports is not defined at vendor-bundle.self-879f615019647c756dc959f99d735b3a2534b00805364ae6fca0091d1190d62d.js?body=1:1
Uncaught TypeError: Cannot read property 'call' of undefined at I (webpack-bundle.self-78221fc03008c178fe970b69731594f14d651dab84e5cf928beacc805ebde79c.js?body=1:1)
This is my webpack.config.js.
const config = {
"entry": {
"webpack-bundle": "./app/registration",
},
"output": {
filename: "[name].js",
path: pathLib.resolve(__dirname, "../app/assets/webpack"),
},
"module": {
"rules": [
{
"exclude": /node_modules/,
"test": /\.jsx?$/,
"use": {
"loader": "babel-loader",
"options": {
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
}
}
],
},
"plugins": [
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
}),
new UglifyJsPlugin(),
],
"optimization": {
"splitChunks": {
"cacheGroups": {
"vendor": {
"test": /node_modules/,
"chunks": "all",
"name": "vendor-bundle"
}
}
}
},
"resolve": {
"alias": {
"Lib": pathLib.resolve(__dirname, "app/lib/"),
"Shared": pathLib.resolve(__dirname, "app/shared/")
},
"extensions": [".js", ".jsx"]
},
"target": "node"
};
module.exports = config;
This is my .babelrc:
{
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
We use React, Rails, React on Rails, and Slim. To load webpack, I'd add this to my application.slim:
= javascript_include_tag 'vendor-bundle'
= javascript_include_tag 'webpack-bundle'
I want to be able to serve the two bundles I created. Is there anything wrong in the way I configured my webpack and split the bundle? Or should I install something else?

At the bottom of your webpack config, you have your target mode set to node
In node, module and module.exports both exist, but these don’t exist in the browser - this is what’s causing the error
If you remove this line, webpack will assume you’re targeting browsers instead, and will also transform this line for you - your bundles should then run in the browser as expected.

Related

Visual Studio Code "Cick-Through / Go-To" does not work with path aliases in jsconfig.json (and Next.js)

I am running a next.js project, as the project grew my imports became harder and harder to read.
Which is why I really love the path aliasing in jsconfig.json. Makes everything so much cleaner.
However, and that's a big however, I used to be able to click on any variable (or import) holding cmd and would be directly taken to the final definition. Same with getting a peek ("Code Peek") into the module/variable that I was importing.
This functionality did not seem to work with aliases. Installing module-resolver helped on the top level. I.e. click-through through is now possible for everything starting with #/Components but not the lower level aliases. Any Idea how to fix that?
Caveats:
I know I should, but I am currently not yet using es-lint,
nor am I explicitly using webpack (I know next.js uses it under the hood)
Plain Javascript (no typescript)
Those tools are surely useful, but I want to keep the additional tooling to a minimum right now.
Configs:
This is my jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/Components/*": ["components/*"],
"#/Concepts/*": ["components/Concepts/*"],
...
}
}
}
this is my .babelrc
{
"presets": ["next/babel"],
"plugins": [
["styled-components", { "ssr": true }],
["module-resolver", {
"root": ["."],
"alias": {
"#/Components": "components",
"#/Concepts": "components/Concepts",
...
}
}]
]
}
I am importing like this (both imports work):
Click-through works:
import { Bold } from "#/Components/styles";
Click-through does not work:
import { DefaultMarginSlider, Formula } from "#/Concepts/utils";
for completeness sake here is my package.json
I got it working with the following config settings
jsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"baseUrl": "src",
"jsx": "react",
"noImplicitAny": false,
"paths": {
"components/*": [
"./components/*"
],
"utils/*": [
"./utils/*"
],
"UI/*": [
"./UI/*"
],
"assets/*": [
"./assets/*"
]
}
},
"exclude": ["node_modules"]
}
my .eslintec file looks like
{
"env": {
"browser": true,
"es6": true
},
"extends": [
"plugin:import/react",
"airbnb"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"settings": {
"import/resolver": {
"alias": {
"map": [
[
"UI",
"./src/UI"
],
[
"components",
"./src/components"
],
[
"assets",
"./src/assets"
]
],
"extensions": [
".js",
".jsx",
".svg",
".png"
]
},
"webpack": {
"config": "config/webpack.config.js"
}
}
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"parser": "babel-eslint",
"plugins": [
"react",
"react-hooks",
"import",
"resolver-alias"
],
"rules": {}
}
And there are the extra plugins I installed to get it working
eslint-import-resolver-alias
eslint-import-resolver-webpack
eslint-plugin-import
And this is my webpack config to resolve while building
resolve: {
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-dom': '#hot-loader/react-dom',
'components': path.resolve(__dirname, '../src/components'),
'assets': path.resolve(__dirname, '../src/assets'),
'UI': path.resolve(__dirname, '../src/UI'),
'utils': path.resolve(__dirname, '../src/utils'),
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
PnpWebpackPlugin,
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
For next.js you can skip the above webpack config and eslint-import-resolver-webpack npm package. It will work fine.

Convert .babelrc to .babelrc.js

I use Material UI and want to make the bundle size smaller by loading the components on demand.
I've got a Babel config in a .babelrc file.
At the moment the .babelrc looks like this:
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
["#babel/plugin-syntax-dynamic-import"],
["react-hot-loader/babel"],
["import", {
"libraryName": "antd",
"style": true
}],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
Now I need to add the following:
const plugins = [
[
'babel-plugin-import',
{
'libraryName': '#material-ui/core',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'core'
],
[
'babel-plugin-import',
{
'libraryName': '#material-ui/icons',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'icons'
]
];
module.exports = {plugins};
How can I do that ? It seems that .babelrc works differently to the .babelrc.js
As indicate in https://babeljs.io/docs/en/config-files:
For compatibility reasons, .babelrc is an alias for .babelrc.json.
So your first script is JSON format and the second one is CommonJS.
Mi suggestion is just copy the contents of plugins from your second script inside the "plugins" section of your first one, and use any JSON validation tool to make sure that the result is correct, see [1]
That being said I suggest that you use .babelrc.cjs (CommonJS) format as it is just javascript code can be formated easily using tools like prettier and support some features that JSON does not like comments, see [2]
[1] .babelrc or .babelrc.json
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
["#babel/plugin-syntax-dynamic-import"],
["react-hot-loader/babel"],
["import", {
"libraryName": "antd",
"style": true
}],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
[
"babel-plugin-import",
{
"libraryName": "#material-ui/core",
"libraryDirectory": "esm",
"camel2DashComponentName": false
},
"core"
],
[
"babel-plugin-import",
{
"libraryName": "#material-ui/icons",
"libraryDirectory": "esm",
"camel2DashComponentName": false
},
"icons"
]
]
}
[2] .babelrc.js or .baberc.cjs
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
["#babel/plugin-syntax-dynamic-import"],
["react-hot-loader/babel"],
["import", {
"libraryName": "antd",
"style": true
}],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
const presets
const plugins = [
[
'babel-plugin-import',
{
'libraryName': '#material-ui/core',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'core'
],
[
'babel-plugin-import',
{
'libraryName': '#material-ui/icons',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'icons'
]
];
module.exports = {plugins};

Jest, how to ignore test coverage of specific folders?

In my react project I have a root ./styles folder which contains various style objects for styled-components. I do not want these files to show up in the coverage test.
I've tried to hide them like so, but when I run npm run coverage they still show up.
package.json
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/jest.setup.js"
],
"coveragePathIgnorePatterns": [
"<rootDir>/styles/",
"./styles/"
],
"testPathIgnorePatterns": [
"<rootDir>/.next/",
"<rootDir>/node_modules/",
"<rootDir>/styles/",
"./styles/"
],
"transform": {
"^.+\\.(js)$": "babel-jest",
"^.+\\.js?$": "babel-jest",
"^.+\\.ts?$": "babel-jest",
"^.+\\.tsx?$": "babel-jest",
"^.+\\.json5$": "json5-jest"
},
"moduleFileExtensions": [
"js",
"json",
"json5",
"ts",
"tsx"
],
"modulePaths": [
"<rootDir>/components/",
"<rootDir>/pages/",
"<rootDir>/shared/"
]
}
babelrc
{
"env": {
"development": {
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}],
["istanbul",{"exclude": ["styles/*.js"]}]
]
},
"production": {
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"test": {
"presets": [
"#babel/preset-typescript",
["next/babel", {"preset-env": { "modules": "commonjs" }}]
],
"plugins": [
["styled-components", { "ssr": true, "displayName": true }],
["#babel/plugin-proposal-decorators", { "legacy": true }],
["babel-plugin-sass-vars"]
]
}
}
}
All I needed was this in package.json
"coveragePathIgnorePatterns": [
"<rootDir>/styles/"
],
And removed it from "testPathIgnorePatterns": <- having it both here and in coveragePathIgnorePatterns caused my tests to run forever and styles still showed up.
I also removed this from the .babelrc:
["istanbul",{"exclude": ["styles/*.js"]}]
Add this to your config (package.json):
modulePathIgnorePatterns: ["directoryNameToIgnore"]
or :
modulePathIgnorePatterns: ["/dist/"]
and :
coveragePathIgnorePatterns: ["/styles/"]

Babel 7 Unexpected token for React component

I'm upgrading to Babel v7 from v6 and when I build the project I get the following error:
Syntax error: src\app\layout\components\FooterToolbar.js: Unexpected token
I'm using the following .babelrc configuration
{
"presets": [
["#babel/preset-env", { "useBuiltIns": "usage", "debug": true }],
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
And finally this is my webpack config. I put the pollyfills first and then the index.js file in the entry and the babel-loader as transpiler
entry: ["#babel/polyfill", paths.appIndexJs],
// Process JS with Babel.
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
exclude: /node_modules/,
include: paths.appSrc,
use: [{ loader: 'babel-loader' }],
},
Any advice to solve this issue? Thanks a lot
EDIT: I'm using typescript in this project. This is the tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"isolatedModules": true,
"strict": true,
"noEmit": true,
"allowJs": true,
"resolveJsonModule": true,
"jsx": "react"
},
"include": [
"src"
]
}
Finally got it to work by updating webpack, its plugins and adding the presets and plugins inside the webpack configuration
// Process JS with Babel.
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
exclude: /node_modules/,
include: paths.appSrc,
use: [{
loader: 'babel-loader',
options: {
presets: [
["#babel/preset-env", { modules: "commonjs" }],
"#babel/preset-typescript",
"#babel/preset-react"
],
plugins: [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
}],
},
Thanks for your answers, hopefully this is useful for someone else

Unexpected token at "async" call with rollup

I have async support with babel working in my project and I've copied and pasted my settings over. I rollup processing past the async declaration. Why can't rollup process async / await? How can I build my code sucessfully?
Error parsing /Users/thomasreggi/Desktop/PAS/PAS-api/src/appProxypass/index.js: Unexpected token (43:44) in /Users/thomasreggi/Desktop/PAS/PAS-api/src/appProxypass/index.js
module.exports = {
exports: 'named',
external: [],
entry: './src/appProxypass/index.js',
dest: './packages/proxypass-app/index.js',
format: 'cjs',
plugins: [
require('rollup-plugin-commonjs')(),
require('rollup-plugin-babel')({
"babelrc": false,
"exclude": 'packages/proxypass-app/node_modules/**',
"include": 'packages/proxypass-app/**',
"runtimeHelpers": true,
"externalHelpers": true,
"plugins": [
"transform-async-to-generator",
"syntax-async-functions",
"transform-flow-strip-types",
"transform-runtime",
"transform-class-properties",
[
"transform-strict-mode",
{
"strict": false
}
]
],
"presets": [
"es2015-rollup",
"stage-2"
]
})
]
}

Categories

Resources