Vite production build fails (React) - javascript

I have a web app created with create-react-app that I am trying to migrate to vite, but it is not working when I build with vite build --minify false.
Everything works well on vite dev version.
Vite 2.9.9,
react: 16.13.1
vite.config.js
import { defineConfig, loadEnv } from 'vite'
import svgr from 'vite-plugin-svgr'
import process from 'process'
import react from '#vitejs/plugin-react'
export default defineConfig(({ command, mode }) => {
// Load env file based on `mode` in the current working directory
const env = loadEnv(mode, process.cwd())
return {
plugins: [
react(),
svgr({
exportAsDefault: false,
// A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should include. By default all svg files will be included.
include: '**/*.svg',
}),
],
build: {
commonjsOptions: {
strictRequires: true,
// transformMixedEsModules: true,
}
}
}
})
Error:
require is not defined on js-cookie (coming from an okta-auth-js dependency).
Research tells me that require should not be used in the browser. So I tried the following option.
I have tried to add in transformMixedEsModules: true to the build options, but that changes the error to:
index.6cd5b200.js:108281 Uncaught TypeError: _typeof$3 is not a function
at _interopRequireWildcard$T (index.6cd5b200.js:108281:23)
at index.6cd5b200.js:108267:1
Am I missing a plugin or something?

Related

Vite Js --> dev mode works, but build doesn't. (importing library causes error)

I tried to move from vue-cli to vite but observed some obstacles.
I want to include several npm packages into my vue 3 project.
I tried to understand the issue, and basically the error came when I imported
https://www.npmjs.com/package/rdf-parse
If I run npm run dev everything works as expected, but when I run npm run build and serve the dist folder with http-server the error:
Uncaught TypeError: Object.defineProperty called on non-object at Function.defineProperty
occurs.
The code worked with vue-cli and in vite-dev mode so I expect I missed somethin crucial in the vite.config.js
But I didnt find anything in the docu that helped me out and also no thread here on stackoverflow or elsewhere.
I created a repo with a minimal example here: https://github.com/stackoverflowuser/vite-issue
It is the npm vue3 template (npm init vue#3) and only the library rdf-parse is added.
// vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url)),
}
},
build: {
target: "es2020"
},
optimizeDeps: {
esbuildOptions: {
// Limit target browsers due to issue: Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari13" + 2 overrides)'
target: "es2020",
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeModulesPolyfillPlugin()
]
}
},
})
In hope someone can give me a hint.

Vite+Vue - Package referenced via npm link can't resolve vite.resolve.alias

I'm developing a package to help other developers here in our company.
I know that I can create aliases to make the code more cleaner and help the readability of it.
So:
PACKAGE PROJECT
vite.config.js
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve:{
preserveSymlinks: false,
alias:{
'#' : path.resolve(__dirname, 'src'),
},
// ....
})
Assume that I've the following folder structure
src
helpers
commonHelper.js
index.js
src/index.js
import {merge} from '#/helpers/commonHelper.js'
export {merge}
PROJECT THAT REFERENCES PACKAGE PROJECT
vite.config.js
It alsos have a vite.config.js with an # alias pointing to it self src
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve:{
preserveSymlinks: false,
alias:{
'#' : path.resolve(__dirname, 'src'),
},
// ....
})
anyfile.js
Lets assume that my package project is called foo and it's referenced using npm link for testing now, after finishing the package it will be referenced using npm install
import {merge} from 'foo'
merge({},{});
When i try to run my project i got the following error
[vite] Internal server error: Failed to resolve import "#/helpers/commonHelper.js" from
"..\..\npmPackages\foo\src\index.js". Does the file exist?
Plugin: vite:import-analysis
File: E:/_Development/foo/src/index.js
3 | import {merge} from '#/helpers/commonHelper.js'
| ^
4 | export {merge}
at formatError (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:40853:46)
at TransformContext.error (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:40849:19)
at normalizeUrl (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37586:33)
at async TransformContext.transform (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37719:47)
at async Object.transform (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:41102:30)
at async loadAndTransform (file:///E:/_Development/project/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37364:29)
As far i noticed the problem is happening because # is pointing to the project that references the foo package
What can i do?
I assume that you're using Vite to build the lib.
In that case using "npm link" or the publishing process, you should point in your package.json of the package using the field "module" to the generated ESM library file instead of the actual source code.
Then you can use the package in your other project same as if it was installed from some package registry.
Please do not use '/src', use '#/' instead

Using non-fully-specified imports with nextjs and webpack 5

I am trying to use a library (a node module I don't control) that contains this import in the packaged code
import _omit from 'lodash/omit';
and it does not work with nextjs12 and webpack5. I get this error
info - Creating an optimized production build
info - Compiled successfully
info - Collecting page data .Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/dev/project/node_modules/lodash/omit' imported from /Users/dev/project/node_modules/library/es/library.js
Did you mean to import lodash/omit.js?
The library has "type": "module" in it, which I think is the cause of this?
I have seen that you need to add fullySpecifed: false, to the webpack loaders, and I have tried that a few different ways.
In my next config, i have
experimental: { esmExternals: true, fullySpecified: false },
I also tried doing this to the config in the webpack function.
config.module.rules.push({
test: /\.m?js$/,
type: 'javascript/auto',
resolve: {
fullySpecified: false,
},
});
Is there something i am missing to make this work? It seems like it might have to do with the fact that this is during "collecting page data" and not "build"?
Node version: 14.16.0
yarn 1

Svelte app shows blank page on first start

This my first time running a Svelte app and I have this issue where the app doesn't seem to know where build/build.css and build/build.js are.
I got the same issue when I tried Svelte with Tailwind.
This is my config when I created the project:
import svelte from 'rollup-plugin-svelte';
import commonjs from '#rollup/plugin-commonjs';
import resolve from '#rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css' }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
This is the ouput after running npm start:
Here is my folder structure:
What went wrong?
This looks very much like the official Svelte template. In this case, the command to build, watch, & serve is npm run dev.
npm start just runs the web server and serve existing files. You'd use it, for example to test your prod build after npm run build.

How to use ES6 import and react in a sailsjs app?

I am trying to update a web app to se the lastest sailsjs and react versions. The app was already using sails v0.12 an react v0.14.x and ES5 style requirejs.config imports like so:
requirejs.config({
urlArgs: "v=" + myapp.buildNumber,
paths: {
'react': '/bower_components/react/react-with-addons',
'reactdom': '/bower_components/react/react-dom',
'label': '/js/shared/reactLabel',
'moment': '/bower_components/moment/moment',
},
shim: {
'reactRedux': ["react"]
}
});
require(['react', 'label', 'moment', 'reactdom', ],
function (React, Label, moment, ReactDOM, ) {
...
Now after updating a ton of npm packages and sails to the latest versions I am trying to get react going on one simple component like so in PCycle.jsx:
import React , {Component } from 'react'
class PCycle extends Component {
render(){
console.log(this.props);
return (
<div className="post card" >hi world</div>
)
}
};
But when I load the page that component is on I get this error and the component does not render.
VM3398 require.js:165 Uncaught Error: Module name "react" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at makeError (VM80 require.js:165)
at Object.localRequire [as require] (VM80 require.js:1429)
at requirejs (VM80 require.js:1791)
at VM1011 pCycle.js:3
Other pages in my app that still use the older react version and require syntax still work so maybe I can use that require syntax on this component too but I would rather be able to do things with import.
I am new to react and babel so I'm not sure if I need some babel magic or what is going on here. Should I post my various config json files? The project like I said is not a new one created with the react cli.
PS:
I have this babel.js file in my /tasks/config folder:
/**
* Compile JSX files to JavaScript.
*
* ---------------------------------------------------------------
*
* Compiles jsx files from `assest/js` into Javascript and places them into
* `.tmp/public/js` directory.
*
*/
module.exports = function(grunt) {
grunt.config.set('babel', {
dev: {
options: {
presets: ["#babel/preset-env",'#babel/react']
},
files: [
{
expand: true,
cwd: 'assets/js/',
src: ['**/*.jsx'],
dest: '.tmp/public/js/',
ext: '.js'
},
{
expand: true,
cwd: 'assets/bower_components/react-notification-system',
src: ['**/*.jsx'],
dest: '.tmp/public/bower_components/react-notification-system',
ext: '.js'
}
]
}
});
grunt.loadNpmTasks('grunt-babel');
};
Maybe those bower_component react-notification-system is somehow messing things up but there is no such folder under assets/bower_components.
I'm not familiar with sailsjs, but if it runs in node, then you will need something to transpile the es6 imports, since node does not support them fully yet.
You could use babel to do this like so:
npm install --save-dev babel-cli babel-preset-env
Then create a .babelrc file in your root to configure and add this:
{"presets": ["env"]}
If you want to bundle files for serving to the client, you can use a bundler like webpack or parcel.

Categories