Exclude certain folders in Vite and Rollup with Vue.js - vue.js

I am using Vite to bundle my Vue.js app, I have #vitejs/plugin-vue and #rollup/plugin-typescript installed.
I would like Vite to skip bundling certain folders inside my src folder:
src > assets
...
src > skins
src > skins > skin1
**src > skins > skin2**
I have tried the exclude option in the vue and typescript plugins, neither work for me. Here is my vite.config.js:
const config = {
mode: process.env.MODE,
root: PACKAGE_ROOT,
resolve: {
alias: {
'/#/': join(PACKAGE_ROOT, 'src') + '/',
},
},
plugins: [vue({
exclude: ['**skin2'],
})],
base: '',
server: {
fs: {
strict: true,
},
},
build: {
sourcemap: true,
target: `chrome${chrome}`,
outDir: 'dist',
assetsDir: '.',
rollupOptions: {
input: join(PACKAGE_ROOT, 'index.html'),
external: [
...builtinModules.flatMap(p => [p, `node:${p}`]),
],
plugins: [
typescript({
exclude: ['**/skin2'],
}),
],
},
}
};
I also tried RegExp which also didn't work, what I've missed? Thank you!

Related

VueLoaderPlugin doies not return HTML used as inline loader for HtmlWebpackPlugin?

With the following webpack.common.js:
const pathtoresolve = require('path');
const paths = require('./paths')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
// Where webpack looks to start building the bundle
entry: [ 'whatwg-fetch', paths.src + '/main.js'],
resolve: {
extensions: [ '.js', '.vue' ],
alias: {
'components': pathtoresolve.resolve(__dirname, '../src/components/'),
'images': pathtoresolve.resolve(__dirname, '../src/images/'),
'styles': pathtoresolve.resolve(__dirname, '../src/styles/'),
}
},
// Where webpack outputs the assets and bundles
output: {
path: paths.build,
filename: '[name].bundle.js',
publicPath: '/',
},
// Customize the webpack build process
plugins: [
// Vue plugin for the magic
new VueLoaderPlugin(),
// Removes/cleans build folders and unused assets when rebuilding
new CleanWebpackPlugin(),
// Copies files from target to destination folder
new CopyWebpackPlugin({
patterns: [
{
from: paths.public,
to: 'assets',
globOptions: {
ignore: ['*.DS_Store'],
},
},
],
}),
// Generates an HTML file from a template
// Generates deprecation warning: https://github.com/jantimon/html-webpack-plugin/issues/1501
new HtmlWebpackPlugin({
title: 'webpack Boilerplate',
favicon: paths.src + '/images/favicon.png',
// TODO This isn't returning HTML. What did it return??
template: '!!vue-loader!' + paths.src + '/App.vue', // template file (explicitly vue)
filename: 'index.html', // output file
}),
],
// Determine how modules within the project are treated
module: {
rules: [
// JavaScript: Use Babel to transpile JavaScript files
{test: /\.vue$/, loader: 'vue-loader' },
{test: /\.js$/, exclude: /node_modules/, use: ['babel-loader']},
// Styles: Inject CSS into the head with source maps
{
test: /\.(scss|css)$/,
use: [
// Note: Only style-loader works for me !!!
// 'vue-style-loader',
'style-loader',
{loader: 'css-loader', options: {sourceMap: true, importLoaders: 1}},
{loader: 'postcss-loader', options: {sourceMap: true}},
{loader: 'sass-loader', options: {sourceMap: true}},
],
},
// Images: Copy image files to build folder
{test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource'},
// Fonts and SVGs: Inline files
{test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: 'asset/inline'},
],
},
}
I get the error:
$ yarn run client-build && yarn run serve
$ node client/build/app.js
building for production...
assets by status 751 KiB [cached] 4 assets
Entrypoint main = js/runtime.06de30f0b0451051a1b0.bundle.js styles/main.3b829f3c5154760383f9.css js/main.ec103c819b2711f469d3.bundle.js
ERROR in unable to locate 'D:\IdeaProjects\AIPlatform\oml\api\client\public' glob
ERROR in Error: The loader "D:\IdeaProjects\AIPlatform\oml\api\client\src\App.vue" didn't return html.
My vue template looks like:
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
But the vue loader was invoked explicitly, so should be returning HTML from my Vue template.
This is using webpack#^5.8.0, html-webpack-plugin#^5.4.0, vue-loader#^15.9.8, and vue-template-compiler#^2.6.14 . (package.json would have been included, except StackOverflow refuses to allow posts that are too dense with code.)
My goal here is to get a html file out of this vue file using webpack. Any suggestions?
Any suggestions?

How configure webpack optimization options in VUE

I have developed a VUE SPA that employs Vuetify as UI.
The starting project was scaffolded using vue-cli and selecting all standard options.
My current vue.config.js file is as follow:
const path = require("path");
const webpack = require("webpack");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
module.exports = {
publicPath: process.env.NODE_ENV == "production" ? "/" : "/",
css: {
sourceMap: true
},
devServer: {
headers: {
"Access-Control-Allow-Origin": "*",
https: true
}
},
productionSourceMap: false,
transpileDependencies: [
"vuetify",
"vue2-dropzone",
"vue-echarts",
"resize-detector"
],
configureWebpack: {
devtool: "source-map",
resolve: {
alias: {
//Api: path.resolve(__dirname, "src/api/"),
Components: path.resolve(__dirname, "src/components/"),
Constants: path.resolve(__dirname, "src/constants/"),
Container: path.resolve(__dirname, "src/container/"),
Views: path.resolve(__dirname, "src/views/"),
Helpers: path.resolve(__dirname, "src/helpers/"),
Themes: path.resolve(__dirname, "src/themes/")
//moment: "moment/src/moment"
},
extensions: ["*", ".js", ".vue", ".json"]
},
plugins: [
//jquery plugin
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"window.jQuery": "jquery",
jQuery: "jquery"
}),
new BundleAnalyzerPlugin(),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
optimization: {
splitChunks: {
chunks: "all"
// minSize: 10000,
// maxSize: 200000
}
}
}
};
I would like to add webpack optimization for minifying css/sass, images, js code, woff2 font files (served locally and not from CDN), I suppose that this is not done automatically, am I wrong?
Could you share a basic configuration to achieve what described above (being able to debug code in development)?

index.html disappears after watch triggered recompilation

I have a Chrome Extension where I started using webpack. I can build it just fine, but in development mode when I am run npm run watch after the first recompilation is triggered the index.html disappears from the build directory.
Here is script part of my package.json:
"build": "node utils/build.js",
"watch": "webpack --watch & webpack-dev-server --inline --progress --colors"
}
My webpack.config.js: (I have a bunch of content scripts listed as separate entry point as well that I omitted)
path = require("path"),
env = require("./utils/env"),
CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin,
CopyWebpackPlugin = require("copy-webpack-plugin"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
WriteFilePlugin = require("write-file-webpack-plugin"),
MiniCssExtractPlugin = require('mini-css-extract-plugin');
const fileExtensions = ["jpg", "jpeg", "png", "gif", "eot", "otf", "svg", "ttf", "woff", "woff2"];
const options = {
mode: process.env.NODE_ENV || "development",
entry: {
// the single js bundle used by the single page that is used for the popup, options and bookmarks
index: path.join(__dirname, "src", "", "index.js"),
// background scripts
"js/backgroundScripts/background": path.join(__dirname, "src", "js/backgroundScripts", "background.js"),
"js/backgroundScripts/messaging": path.join(__dirname, "src", "js/backgroundScripts", "messaging.js")
},
output: {
publicPath: '',
path: path.join(__dirname, "build"),
filename: "[name].bundle.js"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
cache: true,
emitWarning: true
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: true,
},
},
'css-loader',
'sass-loader',
],
},
{
test: new RegExp('\.(' + fileExtensions.join('|') + ')$'),
loader: "file-loader?name=[name].[ext]",
exclude: /node_modules/
},
{
test: /\.html$/,
loader: "html-loader",
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: /node_modules/
},
]
},
resolve: {
modules: [path.resolve(__dirname, './src'), 'node_modules'],
extensions: fileExtensions.map(extension => ("." + extension)).concat([".jsx", ".js", ".css"])
},
plugins: [
// clean the build folder
new CleanWebpackPlugin(),
// expose and write the allowed env vars on the compiled bundle
new webpack.EnvironmentPlugin({
NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false
}),
// copies assets that don't need bundling
new CopyWebpackPlugin([
"src/manifest.json",
{
from: "src/css",
to: 'css/'
},
{
from: "src/_locales",
to: '_locales/'
},
{
from: "src/images",
to: 'images/'
}
], { copyUnmodified: true }),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "index.html"),
filename: "index.html",
chunks: ["index"]
}),
new WriteFilePlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
devServer: {
writeToDisk: true,
contentBase: path.join(__dirname, "../build")
}
};
if (env.NODE_ENV === "development") {
options.devtool = "cheap-module-source-map";
}
module.exports = options;
I can see index.html listed in the initial build log, but not any of the ones after that.
I would appreciate any clues of why this is is happening and how I could fix it. Thanks.
In the plugins section, you should put this line conditional only for production environment:
new CleanWebpackPlugin()
As it's role is to clean the build folder.

How can I make FontAwesome work with vue-cli webpack-simple template?

I generate a default project with vue-cli:
vue init webpack-simple grid-prototype
I install FontAwesome through npm:
npm install --save fontawesome
After that, I include it into main.js with:
import 'font-awesome/css/font-awesome.css'
I execute the app with:
npm run dev
And I get this error:
Failed to compile.
./node_modules/font-awesome/fonts/fontawesome-webfont.ttf?v=4.7.0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/css-loader!./node_modules/font-awesome/css/font-awesome.css 7:684-735
# ./node_modules/font-awesome/css/font-awesome.css
# ./src/main.js
# multi (webpack)-dev-server/client?http://localhost:8082 webpack/hot/dev-server ./src/main.js
Here's my webpack.config.js (it's the default one created by the cli):
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "./dist"),
publicPath: "/dist/",
filename: "build.js"
},
module: {
rules: [
{
test: /\.css$/,
use: ["vue-style-loader", "css-loader"]
},
{
test: /\.vue$/,
loader: "vue-loader",
options: {
loaders: {}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: "file-loader",
options: {
name: "[name].[ext]?[hash]"
}
}
]
},
resolve: {
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue", ".json"]
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: "#eval-source-map"
};
if (process.env.NODE_ENV === "production") {
module.exports.devtool = "#source-map";
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
]);
}
What am I doing wrong?
webpack-simple is suitable for quick prototyping and it doesn't have advanced rules.
Solution #1: Use webpack template instead of webpack-simple to avoid this and other issues in the future.
Solution #2: Use FontAwesome from CDN, for example:
https://www.bootstrapcdn.com/fontawesome/
I mean, just add the CDN css to your index.html
Solution #3: Add one more rule to your webpack config
module: {
rules: [
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
As it is in the webpack template:
https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js

I could not import exported variables from an es2015 NPM module

I have an npm module named sidebar. I use webpack to compile the es2015 src files into a single file. So far running webpack does not output any problem and creates a file, lib/sidebar.min.js
I have set the it to be the main file in package.json
...
"description": "",
"main": "lib/sidebar.min.js",
"scripts": {
...
I have this in my src/index.js file
export const foo = 'foo'
export const bar = 'bar'
I tried using this module in my main project
import { foo, bar } from 'sidebar'
console.log(foo)
console.log(bar)
Both console log calls outputs undefined
After searching the internet for hours, I am totally stumped as to why this is a problem.
Any ideas?
EDIT: Here is the webpack config for the main repository
var webpackConfig = {
entry: {
app: './src/app/main.app.js',
vendor: ['angular']
},
output: {
path: DIST_DIRECTORY + '/scripts/',
publicPath: '/scripts/',
filename: '[name].min.js',
chunkFilename: '[name].min.js'
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
loader: 'babel'
}, {
test: /\.html$/,
loader: 'raw'
}]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true
},
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js")
],
devServer: {
contentBase: DIST_DIRECTORY + '/'
}
};