(vite or rollup) build exoprt name will be change - rollup

I want to try to use vite to package my component library, but I encounter a problem. After packaging, I will change the name of the variable exported from the file
this is vite.config.js:
import { defineConfig } from "vite";
import path from "path";
import { createVuePlugin } from "vite-plugin-vue2";
import pkg from "./package.json";
const inspector = require("inspector");
inspector.open("9292", "127.0.0.1");
const extensions = [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"];
export default (/** if you want to use mode : { mode }*/) =>
defineConfig({
mode: "production",
base: "./",
plugins: [createVuePlugin()],
resolve: {
extensions,
alias: [
{
find: `#gb/utils`,
replacement: path.resolve(__dirname, "../../packages/utils/src"),
},
],
},
css: {
modules: {
scopeBehaviour: "global",
},
preprocessorOptions: {
less: {
javascriptEnabled: true,
charset: false,
},
scss: {
charset: false,
},
},
},
build: {
lib: {
entry: path.resolve(__dirname, "src/index.js"),
name: "index",
formats: ["es"],
fileName: () => `index.js`,
},
cssCodeSplit: true,
outDir: "es",
assetsDir: "style",
watch: {},
minify: "minify",
rollupOptions: {
output: {
// preserveModules: true,
// preserveModulesRoot: "src",
// assetFileNames: ({ name }) => {
// const { ext, dir, base } = path.parse(name);
// console.log(ext, dir, base);
// if (ext !== ".css") return "[name].[ext]";
// return path.join(dir, "style", 'style.css');
// },
chunkFileNames: (chunkInfo) => {
// console.log(chunkInfo);
return "[name].js";
},
manualChunks: (id, { getModuleInfo, getModuleIds }) => {
const filePath = path.parse(id);
const dirPath = filePath.dir
.replace(/.*\/src/, "")
.replace("/", "");
if ([".css", ".scss", ".less"].includes(filePath.ext)) {
return `${dirPath}/style`;
}
if (/vue&type=template&lang/.test(filePath.name)) {
const realName = filePath.name.replace(
/\.vue\?vue\&type\=template\&lang/,
""
);
return `${dirPath}/${realName}`;
}
if (dirPath) {
return `${dirPath}/${filePath.name}`;
}
return `${filePath.name}`;
},
},
external: [
...Object.keys(pkg.devDependencies),
/#gb\/utils.*/,
/node_modules/,
],
},
},
});
this is my code:
export default function (fileUrl = '') {
let file = fileUrl.split('?')[0]
let fileName = file.substring(file.lastIndexOf('/') + 1) || ''
let suffixLastIndex = fileName.lastIndexOf('.')
let name = fileName.substring(0, suffixLastIndex)
let suffix = fileName.substring(suffixLastIndex + 1, fileName.length)
return {
name,
suffix
}
}
when i build, the export name will be a,b,c...z:
function getUrlToFileSuffix(fileUrl = "") {
let file = fileUrl.split("?")[0];
let fileName = file.substring(file.lastIndexOf("/") + 1) || "";
let suffixLastIndex = fileName.lastIndexOf(".");
let name = fileName.substring(0, suffixLastIndex);
let suffix = fileName.substring(suffixLastIndex + 1, fileName.length);
return {
name,
suffix
};
}
export { getUrlToFileSuffix as g };
I need correct name
some people know how to set config?
Thanks so much!

set output.minifyInternalExports = false

Related

How to change filename inside a rule? (Vue CLI 5)

I have this rule, using vue inspect
/* config.module.rule('svg') */
{
test: /\.(svg)(\?.*)?$/,
type: 'asset/resource',
generator: {
filename: 'img/[name][ext]'
}
},
I need to change filename for example to "[contenthash][ext]"
but I cannot do it using
module.exports = defineConfig({
chainWebpack: (config) => {
config.module.rule("svg").generator.filename = "[contenthash][ext]";
},
})
because I cannot set generator ,
I can rewrite all rules using
module.exports = defineConfig({
configureWebpack: (config) => {
config.module.rules = [
{
test: /\.(svg)(\?.*)?$/,
use: [
{
loader: "svg-inline-loader",
options: {
name: "[contenthash].[ext]",
},
},
],
},
];
},
})
but I need other rules to exist... so how can I change fileName of svg?
Try this:
chainWebpack: (config) => {
config.module.rule("svg")
.set('generator', {
filename: "[contenthash][ext]"
})
}
Source

useMeta not updating title in Nuxt Composition API

Here is my code inside the Component Script : Title tag doesn't show up when I inspect
import { useMeta } from "#nuxtjs/composition-api";
export default {
components: { },
head: {},
setup() {
useMeta({
title: 'My title',
meta: [
{
hid: 'description',
name: 'description',
content: 'My description',
},
],
})
const screenType = ref("desktop");
var deviceType = ""
// const screenType = ref("mobile")
// const screenType = ref("landscape")
if (process.browser) {
window.onNuxtReady(() => {
if (window.innerWidth < 500) {
screenType.value = "mobile";
} else {
screenType.value = "desktop";
}
if (navigator.userAgent.match(/mobile/i)) {
deviceType = "mobile";
} else if (navigator.userAgent.match(/iPad|Android|Touch/i)) {
deviceType = "tablet";
} else {
deviceType = "desktop";
}
})
}
} }
There is no head object in my nuxt.config.js
What am I missing here?
Use it like this in your setup function in your Page component with defineComponent :
export default defineComponent({
head: {}, // Needed in nuxt 2
setup() {
const { title, meta } = useMeta()
title.value = 'My title'
meta.value = [
{
hid: 'description',
name: 'description',
content:
'My description',
},
]
},
})
https://composition-api.nuxtjs.org/packages/useMeta
You should use defineComponent imported from "#nuxtjs/composition-api". Do not use defineComponent imported from "#vue/composition-api".

Webpack optimise and compress CSS and Javascript based on production mode inside webpack.config.js

I have the following NPM scripts inside package.json:
"scripts": {
"start": "cross-env NODE_ENV=development webpack --mode development",
"build": "cross-env NODE_ENV=production webpack --mode production"
},
if I run npm run build (production mode) I want to add optimization (see below) to compress my CSS and Uglify the Javascript. How do I achieve that?
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
},
if I run npm start I want to watch the files and further the same as production mode except optimization. I am building a Drupal site so I need to build the assets also in development.
My webpack.config.js looks like this now:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const config = {
entry: {
main: "./src/index.js",
courses: "./src/courses.js",
vendor: "./src/vendor.js"
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].css' }),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
{ from: './src/assets/icons', to: 'assets/icons' }
]),
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: './assets/fonts',
},
},
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
//...
}
if (argv.mode === 'production') {
//...
}
return config;
};
How do I build this in?
I fix it by adjusting webpack.config.js like below:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const config = {
//Entry Point
entry: {
main: "./src/index.js",
courses: "./src/courses.js",
vendor: "./src/vendor.js"
},
//Output
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
//Watch
watch: false,
watchOptions: {
ignored: ['node_modules']
},
//Loader
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
]
},
{
//For fonts
test: /\.(woff|woff2|ttf|otf|eot)$/,
use: [
{
//using file-loader too
loader: "file-loader",
options: {
outputPath: "fonts"
}
}
]
}
]
},
//plugin
plugins: [
new MiniCssExtractPlugin({ filename: '[name].css' }),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
{ from: './src/assets/icons', to: 'assets/icons' }
]),
],
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
//...
config.mode = "development";
config.watch = true;
}
if (argv.mode === 'production') {
//...
config.mode = "production";
config.optimization = {
splitChunks: {
chunks: "all"
},
minimize: true,
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin({
cache: true
})
]
};
}
return config;
};
If anybody have improvements on above, please let me know.

NuxtJs serverMiddleware causing error on production

The NuxtJs app running well with npm run dev but npm run build causing the following error
Here is my server/index.js
require('dotenv').config()
const express = require('express')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const api = require('./api')
const socket = require('./socket')
const host = process.env.HOST
const port = process.env.PORT
app.set('port', port)
// Listen the server
const server = app.listen(port, host)
const io = require('socket.io').listen(server)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console
}
start()
// Online users list by country
app.locals.onlineUsers = {};
// Users who is searching partners
app.locals.searchingUsers = {}
socket.start(io, app)
app.use('/api', api)
module.exports = app
And here is my nuxt.config.js
require('dotenv').config()
const pkg = require('./package')
module.exports = {
mode: 'universal',
debug: true,
serverMiddleware: [
{ path: '/api', handler: '~/server/index.js' }
],
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: 'http://chateg.com/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Fredoka+One|Montserrat:200,400,500,700,800&subset=cyrillic' }
]
},
/*
** Customize the progress-bar color
*/
loading: false,
/*
** Global CSS
*/
css: [
'#/assets/scss/main.scss'
],
/*
** Router middlewares
*/
router: {
middleware: 'i18n'
},
/*
** Plugins to load before mounting the App
*/
plugins: [
{ src: '~/plugins/i18n.js', ssr: true },
{ src: '~/plugins/vue-select.js', ssr: false },
{ src: '~/plugins/vue-flux.js', ssr: false },
{ src: '~plugins/ga.js', ssr: false },
{ src: '~plugins/socket.io.js', ssr: false }
],
/*
** Generate dynamic routes
*/
generate: {
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Nuxt.js modules
*/
modules: [
'#nuxtjs/axios',
'#nuxtjs/router',
'#nuxtjs/sitemap',
['#nuxtjs/component-cache', {
max: 10000,
maxAge: 1000 * 60 * 60
}],
['#nuxtjs/google-analytics', {
id: 'UA-129371850-1'
}]
],
/*
** Generates sitemap
*/
sitemap: {
path: '/sitemap.xml',
hostname: 'http://chateg.com',
cacheTime: 1000 * 60 * 15,
gzip: true,
generate: false, // Enable me when using nuxt generate
exclude: [
'/secret',
'/admin/**'
],
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Axios module configuration
*/
axios: {
baseURL: process.env.BASE_URL
},
/*
** Build configuration
*/
build: {
// analyze: true,
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// config.resolve.alias['vue'] = 'vue/dist/vue.common'
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
Here is my server/api/index.js
const express = require('express')
const router = express.Router()
const request = require('request')
const getPostData = require('../middleware/getPostData')
const help = require('../helper')
router.use(getPostData)
router.post('/login', function (req, res) {
let user = null;
if (req.body.user) {
user = req.body.user;
console.log(user)
}
if (!user.sex || !user.partner || !user.country || !user.token) {
return res.status(400).json({ message: "Something went wrong!" });
}
const verifyCaptchaOptions = {
uri: "https://www.google.com/recaptcha/api/siteverify",
json: true,
form: {
secret: '6Ld4RnQUAAAAAPdZaBbHdginQWteAohILLt1OXuT',
response: user.token
}
}
request.post(verifyCaptchaOptions, function (err, response, body) {
if (err) {
return res.status(500).json({ message: "oops, something went wrong on our side" });
}
if (!body.success) {
return res.status(500).json({ message: body["error-codes"].join(".") });
}
//Save the user to the database. At this point they have been verified.
res.status(201).json({ success: true, user: user });
});
})
router.get('/get_users', function (req, res) {
let numberOfOnlineUsers = 0;
let users = req.app.locals.onlineUsers;
if (Object.keys(users).length) {
for (const key in users) {
if (users.hasOwnProperty(key)) {
numberOfOnlineUsers += help.countArray(users[key]);
}
}
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_users_from_country', function (req, res) {
let numberOfOnlineUsers = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
numberOfOnlineUsers = help.countArray(users[countryId]);
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_males_and_females', function (req, res) {
let males = 0;
let females = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
users[countryId].forEach(item => {
if (item.sex == 'female') {
females++;
} else if (item.sex == 'male') {
males++;
}
})
}
res.status(201).json({ males: males, females: females })
})
module.exports = router
I am sure the bug related to serverMiddleware of nuxt in the config cause when I commented it it is working good but I can't access my API.
Please help me as much as possible. I have not been able to solve this problem for 2 days.

webpack-dev-server does not properly proxy redirect to the backend with hapi and and hapi-auth-cookie

When i boot up the hapi-server as well as the webpack-dev-server and go to localhost:3000/api/login shows a 502 bad gateway and nothing on the page! Thanks for every one who helps
Here is my webpack file:
module.exports = {
entry: ["./index.js"],
output: {
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: {
index: 'index.html'
},
stats: 'normal',
host: process.env.HOST || 'localhost',
port: process.env.PORT || 3000,
proxy: {
'/api/*': {
target: 'http//localhost:9000',
secure: false
}
}
}
};
Here is my hapi-server:
const Hapi = require('hapi');
const Inert = require('inert');
const config = require('./config');
const CookieAuth = require('hapi-auth-cookie');
const server = new Hapi.Server();
server.connection({port: 9000});
const options = {
ops: {
interval: config.hapiGoodInterval
},
reporters: {
console: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ log: '*', response: '*' }]
}, {
module: 'good-console'
}, 'stdout'],
file: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ ops: '*' }]
}, {
module: 'good-squeeze',
name: 'SafeJson'
}, {
module: 'good-file',
args: ['./logs/fixtures/file_log']
}]
}
};
server.register(CookieAuth, (err) => {
if (err) {
throw err;
}
});
server.register(Inert, ()=>{});
server.register({
register: require('good'),
options,
}, (err) => {
if (err) {
return console.error(err);
}
server.start(() => {
console.info(`Server started at ${ server.info.uri }`);
});
});
const cache = server.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
server.app.cache = cache;
server.auth.strategy('session', 'cookie', true, {
password: 'Vaj57zED9nsYeMJGP2hnfaxU874t6DV5',
cookie: 'sid-example',
redirectTo: '/api/login',
isSecure: false,
validateFunc: function (request, session, callback) {
cache.get(session.sid, (err, cached) => {
if (err) {
return callback(err, false);
}
if (!cached) {
return callback(null, false);
}
return callback(null, true, cached.account);
});
}
});
server.route(require('./routes'));
Here are the routes:
var Handlers = require('./handlers');
var Joi = require('joi');
var Routes = [
{
path: '/api/hello',
method: 'GET',
config: {
auth:false,
handler: function (request, reply) {
reply('Hello from the server')
}
}
},
{
method: ['GET', 'POST'],
path: '/api/login',
config: {
handler: Handlers.login,
auth: { mode: 'try' },
plugins: {
'hapi-auth-cookie': { redirectTo: false }
}
}
},
{
path: '/api/logout',
method: 'GET',
handler: Handlers.logout
}
];
And Finally the handlers:
const r = require('rethinkdb');
var {Post, User, Opinion} = require('./rethinkdb/models/all');
class Handlers {
static login(request, reply) {
let username = 'pesho';
let password = '12345';
let uuid = 1;
if (request.auth.isAuthenticated) {
return reply.redirect('/');
}
let message = '';
let account = null;
if (request.method === 'post') {
if (!request.payload.username ||
!request.payload.password) {
message = 'Missing username or password';
}
else {
if (password !== request.payload.password || username !== request.payload.username) {
message = 'Invalid username or password';
}
}
}
if (request.method === 'get' || message) {
return reply('<html><head><title>Login page</title></head><body>' +
(message ? '<h3>' + message + '</h3><br/>' : '') +
'<form method="post" action="/api/login">' +
'Username: <input type="text" name="username"><br>' +
'Password: <input type="password" name="password"><br/>' +
'<input type="submit" value="Login"></form></body></html>');
}
const sid = String(++uuid);
request.server.app.cache.set(sid, { account: account }, 0, (err) => {
if (err) {
reply(err);
}
request.cookieAuth.set({ sid: sid });
return reply.redirect('/');
});
}
static logout(request, reply) {
request.cookieAuth.clear();
return reply.redirect('/');
};
}
module.exports = Handlers;
The problem was kind-a dump, but here it is:
you must add a "/" at the end of the proxy target
proxy: {
'/api/*': {
target: 'http://localhost:9000/',<= This here
secure: false
}
},