I try to use sql.js-httpvfs library inside my project. However, I am not successed yet. I am not expert about node.js.
What I do?
Firstly, need to webpack.config to Gatsby for that I create gatsby-node.js file and add the below code inside it.
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
entry: "./src/index.js",
module: {
rules: [
{
test: "/.tsx?$/",
use: "ts-loader",
exclude: "/node_modules/",
},
],
},
output: {
filename: "bundle.js",
},
devServer: {
publicPath: "/dist",
},
});
};
Inside my index.js page, I add the code;
import { createDbWorker } from "sql.js-httpvfs";
const workerUrl = new URL(
"sql.js-httpvfs/dist/sqlite.worker.js",
import.meta.url
);
const wasmUrl = new URL("sql.js-httpvfs/dist/sql-wasm.wasm", import.meta.url);
function load() {
const worker = createDbWorker(
[
{
from: "inline",
config: {
serverMode: "full",
url: "../myTestDb.sqlite3",
requestChunkSize: 4096,
},
},
],
workerUrl.toString(),
wasmUrl.toString()
);
const result = worker.db.query(`select * from districts`);
document.body.textContent = JSON.stringify(result);
}
load();
But I got error.
There is no any created bundle.js or folder like dist.
Related
I am working on a chrome extension using vuejs currently i have a ready project to start with but it is with webpack.
In the webpack I have multi-entry points some of which lead to generating HTML files and others with javascript only.
with webpack it is clear what is the inputs and how they will be as output in Vite i tried but there is a lot of plugins outdated that work with vuejs 3
this link contains the project
https://stackblitz.com/edit/vue-v83gga
my webpack file is :
const path = require("path");
const fs = require("fs");
// Generate pages object
const pages = {};
function getEntryFile(entryPath) {
let files = fs.readdirSync(entryPath);
return files;
}
const chromeName = getEntryFile(path.resolve(`src/entry`));
function getFileExtension(filename) {
return /[.]/.exec(filename) ? /[^.]+$/.exec(filename)[0] : undefined;
}
chromeName.forEach((name) => {
const fileExtension = getFileExtension(name);
const fileName = name.replace("." + fileExtension, "");
pages[fileName] = {
entry: `src/entry/${name}`,
template: "public/index.html",
filename: `${fileName}.html`,
};
});
const isDevMode = process.env.NODE_ENV === "development";
module.exports = {
pages,
filenameHashing: false,
chainWebpack: (config) => {
config.plugin("copy").use(require("copy-webpack-plugin"), [
{
patterns: [
{
from: path.resolve(`src/manifest.${process.env.NODE_ENV}.json`),
to: `${path.resolve("dist")}/manifest.json`,
},
{
from: path.resolve(`public/`),
to: `${path.resolve("dist")}/`,
},
],
},
]);
},
configureWebpack: {
output: {
filename: `[name].js`,
chunkFilename: `[name].js`,
},
devtool: isDevMode ? "inline-source-map" : false,
},
css: {
extract: false, // Make sure the css is the same
},
};
i finally find out a solution for it as a pre-build template by vitesse written with typescript
https://github.com/antfu/vitesse-webext
in short answer if you want to have multiple entries of HTML files you can add them to the original vite.config.js file
regarding the content.ts file, it needs a different vite.config.content.ts file and we have to call it when we build the project like this
vite build && vite build --config vite.config.content.ts
regarding the vite.config.ts file, the code will be like this written in typescript
/// <reference types="vitest" />
import { dirname, relative } from 'path'
import type { UserConfig } from 'vite'
import { defineConfig } from 'vite'
import Vue from '#vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import WindiCSS from 'vite-plugin-windicss'
import windiConfig from './windi.config'
import { isDev, port, r } from './scripts/utils'
export const sharedConfig: UserConfig = {
root: r('src'),
resolve: {
alias: {
'~/': `${r('src')}/`,
},
},
define: {
__DEV__: isDev,
},
plugins: [
Vue(),
AutoImport({
imports: [
'vue',
{
'webextension-polyfill': [
['*', 'browser'],
],
},
],
dts: r('src/auto-imports.d.ts'),
}),
// https://github.com/antfu/unplugin-vue-components
Components({
dirs: [r('src/components')],
// generate `components.d.ts` for ts support with Volar
dts: r('src/components.d.ts'),
resolvers: [
// auto import icons
IconsResolver({
componentPrefix: '',
}),
],
}),
// https://github.com/antfu/unplugin-icons
Icons(),
// rewrite assets to use relative path
{
name: 'assets-rewrite',
enforce: 'post',
apply: 'build',
transformIndexHtml(html, { path }) {
return html.replace(/"\/assets\//g, `"${relative(dirname(path), '/assets')}/`)
},
},
],
optimizeDeps: {
include: [
'vue',
'#vueuse/core',
'webextension-polyfill',
],
exclude: [
'vue-demi',
],
},
}
export default defineConfig(({ command }) => ({
...sharedConfig,
base: command === 'serve' ? `http://localhost:${port}/` : '/dist/',
server: {
port,
hmr: {
host: 'localhost',
},
},
build: {
outDir: r('extension/dist'),
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r('src/background/index.html'),
options: r('src/options/index.html'),
popup: r('src/popup/index.html'),
},
},
},
plugins: [
...sharedConfig.plugins!,
// https://github.com/antfu/vite-plugin-windicss
WindiCSS({
config: windiConfig,
}),
],
test: {
globals: true,
environment: 'jsdom',
},
}))
the important part of it is this
vite.config.ts
...
build: {
outDir: r('extension/dist'),
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r('src/background/index.html'),
options: r('src/options/index.html'),
popup: r('src/popup/index.html'),
},
},
},
...
Thank you to anyone who tried to help and I hope this will be helpful to others
Regards
My javascript asynchronous function is executed twice but I can't figure out why.
I am using webpack and only one file is loaded on the page this is my articles.js
// articles.js
async function test() {
console.log('test');
}
test().then((items) => {
// code here
}
I have twice "test" in the console
// webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "development",
entry: {
app: "./src/index.js",
articles: "./src/js/pages/articles.js",
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist"),
},
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Translates CSS into CommonJS
MiniCssExtractPlugin.loader,
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
};
Thanks for your help
I'm using my own custom plugin to strip some optional code from a build. This works well, but for some reason it seems to be blocking generation of source maps.
My best guess is that the fact that I'm modifying the index.js output file interferes with the ability to generate a map of for that file. If I comment out the plugin, my source maps come back.
Is there perhaps something I can do to change order of plugin execution that will fix this? Or perhaps a way to strip code from source file input streams (not from the files themselves) rather than from the generated output?
I've tried explicitly adding SourceMapDevToolPlugin to my plugins, but that didn't help.
Here's my webpack.config.cjs file:
const { Compilation, sources } = require('webpack');
const { resolve } = require('path');
module.exports = env => {
const esVersion = env?.esver === '5' ? 'es5' : 'es6';
const dir = env?.esver === '5' ? 'web5' : 'web';
const chromeVersion = env?.esver === '5' ? '23' : '51';
// noinspection JSUnresolvedVariable,JSUnresolvedFunction,JSUnresolvedFunction
return {
mode: env?.dev ? 'development' : 'production',
target: [esVersion, 'web'],
entry: {
index: './dist/index.js'
},
output: {
path: resolve(__dirname, 'dist/' + dir),
filename: `index.js`,
libraryTarget: 'umd',
library: 'tbTime'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: { presets: [['#babel/preset-env', { targets: { chrome: chromeVersion } }]] }
},
resolve: { fullySpecified: false }
}
]
},
resolve: {
mainFields: ['esm2015', 'es2015', 'module', 'main', 'browser']
},
externals: { 'by-request': 'by-request' },
devtool: 'source-map',
plugins: [
new class OutputMonitor {
// noinspection JSUnusedGlobalSymbols
apply(compiler) {
compiler.hooks.thisCompilation.tap('OutputMonitor', (compilation) => {
compilation.hooks.processAssets.tap(
{ name: 'OutputMonitor', stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE },
() => {
const file = compilation.getAsset('index.js');
let contents = file.source.source();
// Strip out dynamic import() so it doesn't generate warnings.
contents = contents.replace(/return import\(.*?\/\* webpackIgnore: true \*\/.*?tseuqer-yb.*?\.join\(''\)\)/s, 'return null');
// Strip out large and large-alt timezone definitions from this build.
contents = contents.replace(/\/\* trim-file-start \*\/.*?\/\* trim-file-end \*\//sg, 'null');
compilation.updateAsset('index.js', new sources.RawSource(contents));
}
);
});
}
}()
]
};
};
Full project source can be found here: https://github.com/kshetline/tubular_time/tree/development
I think using RawSource would disable the source map. The right one for devtool is supposed to be SourceMapSource so the idea looks like following:
const file = compilation.getAsset('index.js');
const {devtool} = compiler.options;
let contents = file.source.source();
const {map} = file.source.sourceAndMap();
// your replace work
// ...
compilation.updateAsset(
'index.js',
devtool
// for devtool we have to pass map file but this the original one
// it would be wrong since you have already changed the content
? new sources.SourceMapSource(contents, 'index.js', map)
: new sources.RawSource(contents)
);
I'm new to aurelia and wanted to add a datepicker in my form, I saw this post from danyow, showing how to add datepicker using jquery. But would love to use a datepicker from bootstrap.
And so I saw this another post, haven't tried the second link because as I'm scanning the node_modules (if it matters, I use the spa templates found here), I saw a folder aurelia-bootstrap-datepicker and under the src folder, there's a aurelia-bootstrap-datepicker.js in which the content is pretty much the same with the second link.
Can I use that folder to have a datepicker? If yes, how? Or should I just follow the second link to create one myself?
What I tried:
use it as feature in my boot.ts file aurelia.use.standardConfiguration().feature(PLATFORM.moduleName('aurelia-bootstrap-datepicker'));
use it as a plugin
require it on my html file
Everything above, nothing is working for me.
Please advise. Thanks
EDIT:
boot.ts
import 'isomorphic-fetch';
import { Aurelia, PLATFORM } from 'aurelia-framework';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap';
declare const IS_DEV_BUILD: boolean; // The value is supplied by Webpack during the build
export function configure(aurelia: Aurelia) {
aurelia.use.standardConfiguration()
.plugin(PLATFORM.moduleName('aurelia-validation'));
if (IS_DEV_BUILD) {
aurelia.use.developmentLogging();
}
aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app/components/app/app')));
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'app': 'aurelia-bootstrapper' },
resolve: {
extensions: ['.ts', '.js'],
modules: ['ClientApp', 'node_modules'],
},
output: {
path: path.resolve(bundleOutputDir),
publicPath: '/dist/',
filename: '[name].js'
},
module: {
rules: [
{ test: /\.ts$/i, include: /ClientApp/, use: 'ts-loader?silent=true' },
{ test: /\.html$/i, use: 'html-loader' },
{ test: /\.css$/i, use: isDevBuild ? 'css-loader' : 'css-loader?minimize' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [
new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new AureliaPlugin({ aureliaApp: 'boot' })
].concat(isDevBuild ? [
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new webpack.optimize.UglifyJsPlugin()
])
}];
}
I have a vue project and installed waypoints
npm install waypoints
I try to import it
import waypoint from 'waypoints';
but get an error
Error: Can't resolve 'waypoints' in /Mypath
What am I doing wrong?
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
var WebpackNotifierPlugin = require('webpack-notifier');
var fs = require('file-system');
var CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
/*node: {
fs: "empty"
},*/
resolve: {
alias: {
'masonry': 'masonry-layout',
'isotope': 'isotope-layout'
}
},
entry: './main.js',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, './public/assets'),
filename: 'bundle.[chunkhash].js',
},
module: {
rules: [
{ test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader?presets[]=es2015",
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: [{loader:'css-loader?sourceMap'}, {loader:'sass-loader', options: {
sourceMap: true,
}}],
})
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
]
},
plugins: [
new CleanWebpackPlugin(['assets/*', 'css/*'], {
root: '/Users/LEITH/sites/laravelleith/public',
verbose: true,
dry: false,
exclude: ['360lockturret.jpg'],
watch: true
}),
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('app.[chunkhash].css'),
new WebpackNotifierPlugin(),
function() {
this.plugin('done', stats =>{
fs.writeFileSync(
path.join(__dirname, 'manifest.json'),
JSON.stringify(stats.toJson().assetsByChunkName)
)
});
}
]
};
Waypoints comes bundled in several flavours, even via NPM, but I couldn't work out if there's a default implementation or not. So that's why your typical import Waypoint from 'waypoints' directive doesn't work.
I resolved this for my "vanilla ES6 + Webpack" setup as follows:
import 'waypoints/lib/noframework.waypoints.min.js';
const waypoint = new Waypoint({
element: document.getElementById('myScrollTarget'),
handler: () => {}
});
Basically #markedup is right, waypoints comes with various flavours, after installing waypoints if you look into /waypoints/lib/ folder you will see zepto|jquery|noframework.waypoints.js .
In this case you would require to import it as full path i.e.
import 'waypoints/lib/noframework.waypoints.min.js';
or
window.waypoint = require('waypoints/lib/noframework.waypoints');