Move index.html from dir in root dir (vite) - javascript

How can i made a move index.html from src/pages/index/index.html to dist/index.html and src/pages/donate/index.html to dist/pages/donate/index.html at a build vite project?
My vite.config.js
import { resolve } from 'path';
import { defineConfig } from 'vite';
const root = resolve(__dirname, 'src');
const outDir = resolve(__dirname, 'dist');
export default defineConfig({
root,
build: {
outDir,
emptyOutDir: true,
rollupOptions: {
input: {
main: resolve(root, 'pages/index/index.html'),
donate: resolve(root, 'pages/donate/index.html')
}
}
}
})

You'll need to use the rollup options in your vite config file.
Something like this should get you going in the right direction:
import { defineConfig } from 'vite';
import { resolve } from 'path';
import path from "path";
export default {
root: path.resolve(__dirname, "src"),
build: {
outDir: path.resolve(__dirname, "dist"),
rollupOptions: {
input: {
index: path.resolve(__dirname, "src/pages/index/index.html"),
donate: path.resolve(__dirname, "src/pages/donate/donate.html"),
},
},
},
};

Related

Vue 3 Vite loading Vuetify/Element plus components in Root not working

I'm trying to load vuetify or element plus components directly into #app.
It only works if I import all components, which of course means a huge file.
If I do manual or automatic import then I get :
Failed to resolve component:
I'm probably missing something in Vite but I can't figure it out.
If I load demo.vue then it works fine.
//Main.js
import { createApp } from 'vue/dist/vue.esm-bundler';
app.component('demo', Demo);
app.mount('#app');
//demo.vue
<el-collapse v-model="activeName" accordion>
<el-collapse-item :title="test" name="1">
<div>
AAA
</div>
<div>
AAA
</div>
</el-collapse-item>
</el-collapse>
If I load the contents of demo.vue in root #conatiner then error, but if I load all components then it works.
import { createApp } from 'vue/dist/vue.esm-bundler';
const app = createApp({
mounted() {
console.log('The app is working')
}
});
const app2 = createApp(App)
app2.mount('#container')
My vite-config
import { defineConfig } from 'vite'
import { fileURLToPath, URL } from 'node:url'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
//base: '/dist/',
plugins: [
vue({
}), AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
], resolve: {
alias: {
'vue': 'vue/dist/vue.esm-bundler',
},
}, build: {
outDir: '../wwwroot/distback',
rollupOptions: {
input: {
front: fileURLToPath(new URL('./qasar/index.html', import.meta.url)),
},
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`
}
}
},
define: { 'process.env': {} },
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url))
},
extensions: [
'.js',
'.json',
'.jsx',
'.mjs',
'.ts',
'.tsx',
'.vue',
],
},
server: {
port: 5000,
},
})

Import JSX file into webpack config

I am trying to import a JSX file into my webpack config. It appears the file imports, but I cannot import modules into that file. I continuously get an error saying Cannot use import statement outside a module
Here is my webpack.config.js:
const bodyParser = require('body-parser')
require('#babel/register')
const render = require('../src/static/render.jsx')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = require('path');
const PATHS = {
app: path.join(__dirname, '../src/static'),
build: path.join(__dirname, '../src/static_dist')
};
const basePath = path.resolve(__dirname, '../src/static/');
module.exports = {
mode: 'development',
devtool: 'cheap-module-eval-source-map',
output: {
filename: '[name].js',
path: PATHS.build,
publicPath: '/static/'
},
devServer: {
before: function(app) {
app.use(bodyParser.json({ limit: '10mb' }))
app.post('/render', function (req, res) {
res.sendStatus(204);
const initialState = {} //buildInitialState(req.body)
const result = render(url, initialState)
res.json({
html: result.html,
finalState: result.finalState
})
});
},
// Render.jsx
require('#babel/register');
import React from 'react' <-- error happens here
import { Provider } from 'react-redux'
import { match, RouterContext } from 'react-router'
import ReactDOMServer from 'react-dom/server'
import configureStore from './store/configureStore';
import { createBrowserHistory } from "history";
import { routes } from "../routes.js";
import AdminNavbar from "./components/Navbars/AdminNavbar.jsx";
import Sidebar from "./components/Sidebar/Sidebar.jsx";
export default function render (url, initialState) {
... a function ...
}
I feel like I have tried everything! Tinkering with babel, adding #babel/register, adding a .babelrc, changing how it is imported, etc.
You likely need to tell Webpack to resolve that particular extension.
Here's the documentation on resolve: Resolve
The code:
module.exports = {
//...
resolve: {
extensions: ['.js', '.jsx']
}
};
Also I notice you haven't specified your entry. If the solution above doesn't work, try specifying the following:
module.exports = {
//...
entry: './src/Render.jsx'
};
Docs: Entry Point
You likely have to do both.

How to Export multiple classes in a single library in Javascript?

I have two JS classes in different files like this:
// Class1.js
export default class Class1 { /* ... */ }
// Class2.js
import Class1 from './Class1'
export default class Class2 { /* ... */ }
And an index.js file that exports both
// index.js
import Class1 from './Class1'
import Class2 from './Class2'
export default {Class1, Class2}
And I'm using webpack to bundle them
// webpack.config.js
const path = require('path')
module.exports = {
devtool: 'source-map',
optimization: {
runtimeChunk: true
},
entry: './src/index.js',
output: {
filename: 'my-lib.js',
path: path.resolve(__dirname, 'dist'),
library: 'MyLib'
},
mode: 'development',
target: 'node',
}
// package.json
{
"name": "my-lib",
"version": "0.1.0",
"main": "dist/my-lib.js",
"module": "src/index.js",
"private": true,
"scripts": {
"build": "webpack"
}
}
However, when I try to use them in a separate project:
// MyComponent.js
import {Class2} from 'my-lib'
I get this warning:
WARN in ./MyComponent.js
"export 'Class2' was not found in 'my-lib'
Why? It's clearly being exported in the index.js file. How can I fix this? Is there even a right way to do this or do I have to create a different library for every class I need?

React useState is undefined working with webpack-dev-server

I am building a simple react app with React hooks and webpack-dev-server. I would like to enable hot reload.
Running the webpack-dev-server --mode development, I got an error: TypeError: Object(...) is not a function and It complains at the folloing line which is compiled.
var _useState = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(0),
This is my code
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/index.jsx',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx'],
mainFiles: ['index']
},
output: {
path: path.join(__dirname, 'public'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: './public',
hot: true
}
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"react-hot-loader/babel"
]
}
Body.jsx
import React, { useState } from 'react';
const Body = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>{`You clicked ${count} times`}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};
export default Body;
App.jsx
import React from 'react';
/* eslint-disable import/no-extraneous-dependencies */
import { hot } from 'react-hot-loader/root';
import { setConfig } from 'react-hot-loader';
import Body from './Body';
const App = () => (
<div className="App">
<Body />
</div>
);
export default hot(App);
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('app'));
For dependencies, I am using react and react-dom with version 16.7.0-alpha.2.
react-hot-loader is version 4.6.3
Sadly react-hot-loader is not compatible with hooks, atleast to my knowledge and their issue github page.
https://github.com/gaearon/react-hot-loader/issues/1088

React-hot-loader not re-rending components

I have an application that is serving an EJS view with my React.js bundle loaded in a script tag.
I have followed the instructions for react-hot-loader v3 and #next, neither are working. The are no errors in the console and the components are not being re-rendered on change.
Here is my app entry point:
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { AppContainer } from 'react-hot-loader'
import { store } from './routes';
import App from './containers/App';
const render = Component => {
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider>
<AppContainer>
<Component />
</AppContainer>
</MuiThemeProvider>
</Provider>,
document.getElementById('root'))
};
render(App);
//registerServiceWorker();
// Webpack Hot Module Replacement API
if (module.hot) {
console.log('module.hot exists');
module.hot.accept('./containers/App', () => {
console.log('Reloading app');
render(App);
})
}
Here is the App files that the entry point is calling:
import React from 'react';
import Navigation from '../components/Navigation';
import { hot } from 'react-hot-loader'
import createRoutes from '../routes';
const routes = createRoutes();
const App = () => {
return ([
<Navigation key="app-navigation" />,
<main style={{ height: 'calc(100% - 85px)' }} key="app-main">{routes}</main>
])
};
export default hot(module)(App)
Here is my webpack dev config:
const devBrowserRender = {
devtool: 'source-map',
context: PATHS.app,
entry: {
app: ['babel-polyfill', 'react-hot-loader/patch',
'./index']
},
node,
devServer: {
contentBase: PATHS.assets,
hot: true
},
output: {
path: PATHS.assets,
filename: '[name].dev.js',
publicPath: PATHS.public
},
module: { rules: rules({ production: false, browser: true }) },
resolve,
plugins: plugins({ production: false })
};
Here are my JavaScript rules:
const presets = [["es2015", { "modules": false }], 'react', 'stage-0'];
const plugins = production ? [
'transform-react-remove-prop-types',
'transform-react-constant-elements',
'transform-react-inline-elements'
] : [];
return {
test: /\.js$|\.jsx$/,
loader: 'babel-loader',
options: {
presets,
plugins
},
exclude: PATHS.modules
};
Developer plugins:
if (!production) {
return [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.EnvironmentPlugin(['NODE_ENV']),
new webpack.DefinePlugin(compileTimeConstantForMinification),
new ExtractTextPlugin({
filename: '[contenthash].css',
allChunks: true
}),
// new webpack.optimize.UglifyJsPlugin({ compress }),
new ManifestPlugin({
fileName: 'manifest.json'
})
];
}
I'm assuming this is coming from a misunderstanding about how react-hot-loader works, but I cannot find any other information about why it wouldn't work in the docs or examples.
I know the pain of configuring this stuff.
You need to include the next lines in your entry section
entry: {
app: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index.js'
]
}
then when you are setting babel-loader configuration you need to add react-hot-loader/babel
const plugins = production ? [
'transform-react-remove-prop-types',
'transform-react-constant-elements',
'transform-react-inline-elements'
] : ['react-hot-loader/babel'];
Here I have a simple configuration with this feature.
Hope it helps.

Categories

Resources