Externalize pdf.js in an npm module with webpack - vue.js

I'm currently building some kind of UI Component library on top of vue.js and vuetify. One component is some pdf viewer, which uses pdf.js to render the pdf. All external libraries hould be excluded from the bundle and will be instead installed in the "consuming" project.
I'm loading pdfjs like this in my SFC:
import pdfJs from 'pdfjs-dist/webpack'
function getDocument(url) {
return pdfJs.getDocument(url).promise
}
To build the npm module I've setup the project using vue-cli and changed the webpack config in vue.config.js like this:
module.exports = {
configureWebpack: {
resolve: {
symlinks: false
}
},
chainWebpack: config => {
if (process.env.NODE_ENV === 'production') {
config.externals({
vuetify: 'vuetify',
lodash: 'lodash',
axios: 'axios',
pdfJs: 'pdfjs-dist/webpack'
})
}
},
css: {
loaderOptions: {
sass: {
implementation: require('sass')
}
}
}
}
For all the listed libraries like vuetify, lodash and axios the externalization works without problems. Only pdf.js and its pdf.worker.js still appears in the bundle. How can I externalize pdf.js from the bundle?

WebpackConfig:
{
optimization: {
splitChunks: {
cacheGroups: {
pdf: {
name: `chunk-pdf`,
test: /[\\/]pdfjs-dist[\\/]/,
chunks: 'initial'
}
}
}
}
}

Related

How to configure css output file webpack 5 vue.js 3?

I'm trying to configure vue.js webpack for development mode. I have a separate folder in root directory named "styles" where I keep all my scss and include main.scss to main.js. I want to have the separate css file in the dist folder.
There is my vue.config.js:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'development') {
return {
plugins: [new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename:'[name].css'
})],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
}
}
}
}
Screen Result

Storybook/Vue: style not applied

I installed storybook via the vue-cli and added a .scss file in my preview.js:
import "assets/scss/core.scss";
import Vue from "vue";
import CompositionApi from "#vue/composition-api";
Vue.use(CompositionApi);
where "assets" is an alias configured in my vue.config.js to refer to the src/assets path. According to the docs :
The webpack config used for storybook is resolved from vue-cli-service, which means you don't need to have any special webpack section in storybook config folder.
So the path should ne correctly resolved, right ? However the style does not seem to be loaded as it is not applied to my components.
Am I missing something ?
FYI, here is my main.js:
module.exports = {
core: {
builder: "webpack5",
},
stories: ["../../src/**/*.stories.#(js|jsx|ts|tsx|mdx)"],
addons: [
"#storybook/addon-essentials",
"#storybook/addon-links",
],
};
And my vue.config.js :
const path = require("path");
module.exports = {
configureWebpack: {
resolve: {
alias: {
//aliases go here
"#": path.resolve(__dirname, "src"),
assets: path.resolve(__dirname, "./src/assets"),
},
},
},
css: {
loaderOptions: {
scss: {
additionalData: `#import 'assets/scss/variables';`,
},
},
},
};
Thanks !

Wrong import path after building vue proect as a "Library"

I am currently coding a small vue component library for company's internal use. However, I faced some difficulties on building and deploy the project. This component library contains several components inside. And it will finally build by vue-cli-service build --target lib. The problem I am facing right now is that I have a component (i.e. called Audio.vue), and it will import a .mp3 file inside the component. The component is look like this
<template>
<audio controls :src="soundSrc" />
</template>
<script>
import { defineComponent } from 'vue';
import sound from './assets/sound.mp3';
export default defineComponent({
name: 'Audio',
props: {},
setup() {
return { soundSrc: sound };
},
});
</script>
<style scoped></style>
However, I use this component by serving (vue-cli-service serve") my project is fine. But if I build this project by running vue-cli-service build --target lib --name project-name-here. And I use this built version as a git submodule of my library in another vue project by importing project-name-here.common built before. The sound.mp3 import from './assets/sound.mp3' could not be found. It seems it is using a relative path of my another vue project (i.e. localhost:8080) instead of the library project
Here is my vue.config.js
const path = require('path');
module.exports = {
css: {
extract: false,
},
lintOnSave: false,
productionSourceMap: false,
configureWebpack: {
resolve: {
alias: {
mediaAsset: path.resolve(__dirname, './src/components/Audio/assets'),
},
},
},
chainWebpack: (config) => {
const imgRule = config.module.rule('images');
imgRule
.use('url-loader')
.loader('url-loader')
.tap((options) => Object.assign(options, { limit: Infinity }));
const svgRule = config.module.rule('svg');
svgRule.uses.clear();
svgRule
.test(/\.svg$/)
.use('svg-url-loader') // npm install --save-dev svg-url-loader
.loader('svg-url-loader');
config.module
.rule('raw')
.test(/\.txt$/)
.use('raw-loader')
.loader('raw-loader');
config.module
.rule('media')
.test(/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/)
.use('url-loader')
.loader('url-loader')
.tap((options) =>
Object.assign(options, {
limit: 4096,
fallback: {
loader: 'file-loader',
options: {
name: 'media/[name].[hash:8].[ext]',
},
},
})
);
},
};
Appreciated for answering this question. Thanks.

Disable Dart SASS Warnings Produced By External Theme File

I have a third party SCSS file that I am including in my project, and Dart SASS is displaying a long list of warnings as a result. How can I disable the warnings for third party includes?
I'm using Vue with Dart SCSS. Dart has a quietDeps option, but I'm not sure if I'm using it the right way.
// _common.scss
// Line below causes warnings to be displayed.
#import "~#progress/kendo-theme-default/dist/all";
// ...
// Vue.config.js
module.exports = {
// ...
css: {
loaderOptions: {
sass: {
prependData: '#import "~#/styles/common";',
sassOptions: {
quietDeps: true
}
}
}
}
}
See the following issues: https://github.com/webpack-contrib/sass-loader/issues/954 and https://github.com/sass/sass/issues/3065.
The quietDeps option isn't exposed yet to the Node.js API.
In the meantime you can downgrade to sass 1.32 without too many changes.
EDIT: It's now available in sass 1.35.1.
For anyone who looking for Encore configuration
Encore.enableSassLoader((options) => {
options.sassOptions = {
quietDeps: true, // disable warning msg
}
})
For NuxtJS add this to nuxt.config.js
build: {
loaders: {
scss: {
sassOptions: {
quietDeps: true
}
}
}
}
For anyone working with vue + quasar, what worked for me is tweaking the config to be as follows:
const path = require("path");
module.exports = {
outputDir: path.resolve(__dirname, "../API/ClientApp/dist"),
pluginOptions: {
quasar: {
importStrategy: "kebab",
rtlSupport: false,
},
},
css: {
loaderOptions: {
sass: {
sassOptions: {
quietDeps: true
}
}
}
},
transpileDependencies: ["quasar"],
};

import { ipcRenderer } from 'electron' produces this error: __dirname is not defined

With this simple vue page:
<template>
<div class="home">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from '#/components/HelloWorld.vue'
import { ipcRenderer } from 'electron'
export default {
name: 'Home',
components: {
HelloWorld
},
data() {
return {
dato: null
}
},
methods: {
rendererFunct () {
//ipcRenderer.on('setting', (event, arg) => {
//console.log(arg);
//})
}
}
}
</script>
The only presence of import { ipcRenderer } from 'electron' produces the error __dirname is not defined :
Is this problem is something related to webpack configuration or it is due to something else?
This is my webpack.config.js :
import 'script-loader!./script.js';
import webpack from 'webpack';
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
target: ['electron-renderer', 'electron-main', 'electron-preload'],
pluginOptions: {
electronBuilder: {
chainWebpackMainProcess: config => {
config.resolve.alias.set('jsbi', path.join(__dirname, 'node_modules/jsbi/dist/jsbi-cjs.js'));
}
},
},
};
module.exports = {
entry: './src/background.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
module.exports = config => {
config.target = "electron-renderer";
return config;
};
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: 'source', to: 'dest' },
{ from: 'other', to: 'public' },
],
options: {
concurrency: 100,
},
}),
],
};
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
};
const supportedLocales = ['en-US', 'it'];
export default const config = {
plugins: [
new webpack.ContextReplacementPlugin(
/date\-fns[\/\\]/,
new RegExp(`[/\\\\\](${supportedLocales.join('|')})[/\\\\\]index\.js$`)
)
]
}
This is vue.config.js :
module.exports = {
configureWebpack: {
// Configuration applied to all builds
},
pluginOptions: {
electronBuilder: {
chainWebpackMainProcess: (config) => {
// Chain webpack config for electron main process only
},
chainWebpackRendererProcess: (config) => {
config.plugin('define').tap((args) => {
args[0]['IS_ELECTRON'] = true
return args
})
},
mainProcessFile: 'src/background.js',
mainProcessWatch: ['src/preload.js'],
}
}
}
module.exports = {
pluginOptions: {
electronBuilder: {
disableMainProcessTypescript: false,
mainProcessTypeChecking: false
}
}
}
Electron: version 9.0.0
webpack: version 4.44.1
System:
OS: Linux 5.4 Ubuntu 18.04.4 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-4790K CPU # 4.00GHz
Binaries:
Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node
Yarn: 1.22.4 - /usr/bin/yarn
npm: 6.14.5 - ~/.nvm/versions/node/v14.5.0/bin/npm
Browsers:
Chrome: 84.0.4147.105
Firefox: 79.0
Looking forward to your kind help.
Marco
__dirname is a NodeJS variable, in recent electron versions, node integration is disabled by default. When opening your BrowserWindow, you should add the following to the options:
webpreferences:{
nodeIntegration: true
}
This is however STRONGLY DISCOURAGED as this opens up security issues.
this seems to solve it for most people (for me sadly enough i now get the next error:
fs.existsSync is not a function)
a better solution i to change your bundler to the correct build mode. You should not be building for node but for web, so target:esnext or something.
if something requires node access, this should be solved by running it in the background thread or the preload scripts.
You can apply the solution described on this post
How to import ipcRenderer in vue.js ? __dirname is not defined
In this way you can call this method from vue files:
window.ipcRenderer.send(channel, args...)
Just make sure you configure preload.js on vue.config.js:
// vue.config.js - project root
module.exports = {
pluginOptions: {
electronBuilder: {
preload: 'src/preload.js' //make sure you have this line added
}
}
}