How to configure Vite to run eslint after building? - vite

I'm trying to run eslint AFTER vite bundles my code
import eslint from 'vite-plugin-eslint'
const outDir = 'out'
export default defineConfig({
plugins: [
{
...eslint({
include: outDir + '/**/*',
overrideConfigFile: '.eslintrc.js',
fix: true,
failOnError: true,
failOnWarning: true
}),
enforce: 'post',
apply: 'build',
}
],
build: {
emptyOutDir: false,
outDir,
sourcemap: false,
watch: {},
minify: false,
lib: {
entry: {
server_scripts : "./src/server/index.ts",
startup_scripts : "./src/startup/index.ts",
client_scripts : "./src/client/index.ts",
},
fileName: '[name]/bundle',
formats: ["cjs"],
},
},
})
here's what i have so far, i thought doing enforce:'post' should work but it doesn't, eslintrc already has the rules and doing eslint --fix manually fixes it. and i'm sure it's using the right eslint because it throws the error when i do lintOnStart option

Related

How to resolve conflicts between prettier and eslint

I have set up both prettier and eslint in my node.js project. But I am getting huge amounts of conflicts and syntax errors.
I followed dev.to documentation to set up prettier and eslint and make them compatible with each other.
// .eslintrc.js
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
},
extends: ['standard', 'prettier'],
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
},
rules: {
'prettier/prettier': 'error',
quotes: ['error', 'single'],
semi: ['error', 'always'],
},
plugins: ['prettier'],
};
//.prettierrc.js
module.exports = {
trailingComma: 'es5',
tabWidth: 1,
semi: true,
singleQuote: true,
};

How to transpile npm module with "optional chaining" code to earlier version of node?

Currently I am running node v16.13.1 and I wrote small npm package I would like to publish to npm and then install globally and run as executable.
Application works fine when built with current version but because I am using "optional chaining" (object?.something) it does not work with node 12.
I do not want to change code, but I would like to transpile it so it runs it in all node versions between 12 and 16+.
My webpack look like this:
const path = require("path");
const webpack = require("webpack");
module.exports = (env, argv) => {
console.log('Log::', env, argv);
const config = {
entry: './src/index.js',
devtool: (argv.mode === 'development') ? 'cheap-module-source-map' : undefined,
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
experiments: {
outputModule: true,
},
plugins: [
//empty pluggins array
new webpack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),
],
module: {
// https://webpack.js.org/loaders/babel-loader/#root
rules: [
{
test: /.m?js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}
],
},
resolve: {
fallback: {
"fs": false,
"path": false,
"os": false,
assert: require.resolve('assert'),
path: require.resolve('path-browserify'),
util: require.resolve('util'),
},
},
target: "node12.22"
};
console.log('Log::', config);
return config;
}
and this is .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
]
}
running npm build with target: "node" gives following error:
Error: For the selected environment is no default ESM chunk format available:
ESM exports can be chosen when 'import()' is available.
running it with target: "node12.22" does not give any errors but when I try to run I get:
SyntaxError: Cannot use import statement outside a module
←[90m at Object.compileFunction (node:vm:352:18)←[39m
If I remove target:"node" all together I am getting following error when run:
TypeError: s.existsSync is not a function
If I run it without fallback: { "fs": false then I get compile errors:
Module not found: Error: Can't resolve 'fs' in
Try adding the following to your Webpack config to have the optimizer output code that's compatible with ECMA 6, which does not include optional chaining:
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
ecma: 6,
mangle: false,
// compress: false, // NOTE: Not certain you can just pass false here, but I think probably
},
}),
],
},
And be sure to install the TerserJS Plugin and require it in your config, const TerserPlugin = require('terser-webpack-plugin');

Extract local and global styles with mini-css-extract-plugin

Until now I have been using extract-text-webpack-plugin and webpack 3 to make two bundle files. One for local styles and one for gloabl styles.
So in global styles file we would extract css from like bootstrap, semantic ... and in local styles bundle we would put our own styles.
Both of those files would have contenthash so if for example I change something in my local styles and rebuild app, only the hash from local styles would change and not from globaly styles.
After updateing to webpack 4 a need to use mini-css-extract-plugin instead of extract-text-webpack-plugin.
This was my setup until now. I am trying different things but I dont know how to turn this setup for mini-css-extract-plugin?
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ExtractLocal = new ExtractTextPlugin({
filename: 'stylesheet/stylesLocal.[contenthash].local.css',
disable: false,
allChunks: true,
})
const ExtractGlobal = new ExtractTextPlugin({
filename: 'stylesheet/stylesGlobal.[contenthash].css',
disable: false,
allChunks: true,
})
module.exports = {
module: {
rules: [
/* Local styles */
{
test: /\.local\.(css|scss)$/,
use: ExtractLocal.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize: true,
modules: true,
importLoaders: 1,
localIdentName: '[local]___[name]__[hash:base64:5]',
},
},
...
],
}),
},
/* Global styles */
{
test: /^((?!\.local).)+\.(css)$/,
use: ExtractGlobal.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize: true,
},
},
],
}),
},
],
},
plugins: [
ExtractLocal,
ExtractGlobal,
...
],
}
Your css loaders are correct.
In plugins, I see you want implement it using mini-css to extract multiple css files.
While it's definitely an options, I succeeded implementing it with webpack Optimization option, and only 1 mini-css in plugins.
Output config:
output: {
path: appConfig.paths.appBuild,
filename: 'scripts/[name].[chunkhash:8].js',
chunkFilename: 'scripts/[name].[chunkhash:8].chunk.js',
publicPath: publicPath,
},
Additional css rule for styles from node modules only (I made it the first css rule and after it the additional rules):
{
test: /\.(css|scss)$/,
include: /(node_modules)/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
Optimization config:
(This will extract vendor js as well.)
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
Plugin config:
new MiniCssExtractPlugin({
filename: 'styles/[name].[contenthash].css',
chunkFilename: 'styles/[name].[contenthash].css',
}),

Bundle sha3/binary modules with Webpack

Webpack warns when I bundle my source as it can't resolve the 'sha3' module.
$ npm run build
WARNING in ./~/keccakjs/index.js
Module not found: Error: Can't resolve 'sha3' in '<PROJ>\node_modules\keccakjs'
# ./~/keccakjs/index.js 2:19-34
# ./~/<lib>/index.js
# ./lib/<file>.js
Reason being the sha3 library has no js files.
Creating library <proj>\node_modules\sha3\build\Release\sha3.lib and object <proj>\node_modules\sha3\build\Release\sha3.exp
I am able to run require('sha3') in my project, however webpack cannot resolve it.
I looked at the docs here, regarding how webpack resolves libs.
Could someone point me to how I can include sha3 in/with my bundle.
My Webpack config:
module.exports = {
target: 'node',
entry: "./<lib>.js",
devtool: "source-map",
node: {
__dirname: false,
__filename: false,
},
output: {
path: "./dist",
filename: "<lib>.min.js"
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
}
What actually ended up working for me was:
resolve: {
alias: {
sha3: path.join(__dirname,'node_modules/sha3/build/Release/sha3.node')
},
},
module: {
rules: [
{test: /\.node$/, use: 'node-loader'},
]
},
That way I told it which file to import, when it wasn't able to resolve sha3. And the node-loader packages in the .node file!
Try using the binary loader from webpack from here. Then you can:
1) Define loaders in your WebPack config:
module.exports = {
target: 'node',
entry: "./<lib>.js",
devtool: "source-map",
node: {
__dirname: false,
__filename: false,
},
output: {
path: "./dist",
filename: "<lib>.min.js"
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
],
module: {
loaders: [
{ test: /sha3$/, loader: 'binary' }
]
}
}
2) Use the loader directly in your import:
require('binary!sha3');

"npm run" hanging on ts-loader (webpack)

I am building a web app that consists of static HTML and other assets using webpack on Mac OS X 10.11.3. The app talks to an API that is on another server.
I am having trouble building my app using webpack. The build process appears to hang at or around the ts-loader execution. I am running my build like this:
npm run go --loglevel verbose
which executes this command from my package.json:
./node_modules/.bin/webpack-dev-server --display-reasons --display-chunks --watch
The output in the Terminal window ends with
ts-loader: Using typescript#1.7.5 and /Users/mn/Documents/source/J/appstore/store-front/app/ts/tsconfig.json
I have tried deleting the node_modules folder and reinstalling these; I have tried uninstalling webpack and reinstalling; I have tried reverting my webpack.config.js to a version I know works; but it just hangs here!
My webpack.config.js looks like this:
var webpack = require('webpack'),
ReloadPlugin = require('webpack-reload-plugin'),
path = require('path'),
ChunkManifestPlugin = require('chunk-manifest-webpack-plugin'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
WebpackNotifierPlugin = require('webpack-notifier'),
ExtractTextPlugin = require("extract-text-webpack-plugin");
/**
* optimist has been depracted. Find an alternative? minimist?
*/
var argv = require('optimist')
.alias('r', 'release').default('r', false)
.argv;
/**
* Useful variables
*/
var cwd = process.cwd();
var DEBUG = !argv.release;
var isDevServer = process.argv.join('').indexOf('webpack-dev-server') > -1;
var version = require(path.resolve(cwd, 'package.json')).version;
var reloadHost = "0.0.0.0";
var npmRoot = __dirname + "/node_modules";
var appDir = __dirname + "/app";
var entry = ["./app/ts/bootstrap"]
if (isDevServer) {
entry.unshift("webpack-dev-server/client?http://" + reloadHost + ":8080");
}
function makeConfig(options) {
return {
cache: true,
debug: true,
verbose: true,
displayErrorDetails: true,
displayReasons: true,
displayChunks: true,
context: __dirname,
entry: {
app: entry,
vendor: './app/ts/vendor.ts'
},
stats: {
colors: true,
reasons: DEBUG
},
devtool: 'source-map',
recordsPath: path.resolve('.webpack.json'),
devServer: {
inline: true,
colors: true,
contentBase: path.resolve(cwd, "build"),
publicPath: "/"
},
output: {
path: path.resolve(cwd, "build"),
filename: "[name].js",
publicPath: "/",
chunkFilename: "[id].bundle.js",
// Hot Module Replacement settings:
hotUpdateMainFilename: "updates/[hash].update.json",
hotUpdateChunkFilename: "updates/[hash].[id].update.js"
},
plugins: [
new webpack.IgnorePlugin(/spec\.js$/),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] }),
new ExtractTextPlugin("styles.css"),
new webpack.DefinePlugin({
VERSION: JSON.stringify(version),
ENV: JSON.stringify(options.env)
}),
new HtmlWebpackPlugin({
template: path.join(appDir, "index.html"),
}),
new ReloadPlugin(isDevServer ? 'localhost' : ''),
new WebpackNotifierPlugin({
title: "Jisc AppStore App"
}),
],
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
modulesDirectories: ['node_modules'],
fallback: path.join(__dirname, "node_modules")
},
resolve: {
root: [path.resolve(cwd)],
modulesDirectories: [
'node_modules', 'app', 'app/ts', '.'
],
extensions: ["", ".ts", ".js", ".json", ".css"],
alias: {
'app': 'app',
'scripts': npmRoot
}
},
module: {
preLoaders: [
{ test: /\.ts$/, loader: "tslint" }
],
loaders: [
{ test: /\.(png|jp?g|gif)$/, loaders: ["url", "image"] },
{ test: /\.json$/, loader: 'json' },
{ test: /^(?!.*\.min\.css$).*\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader?sourceMap") },
{ test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap'] },
å { test: /\.html$/, loader: "html" },
{ test: /\.ts$/, loader: 'ts', exclude: [/test/, /node_modules/] },
{ test: /vendor\/.*\.(css|js)/, loader: 'file-loader?name=[path][name].[ext]', exclude: [/node_modules/] },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
],
noParse: [
/\.min\.js/,
/vendor[\/\\].*?\.(js|css)$/
]
},
tslint: {
emitErrors: false,
failOnHint: false
}
}
}
var config = makeConfig(argv)
console.log(require('util').inspect(config, { depth: 10 }))
module.exports = config;
My tsconfig.json looks like this:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmitHelpers": false,
"sourceMap": true
},
"filesGlob": [
"./app/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}
Can anyone suggest what might be happening? I don't seem to be able to produce any logs from either the webpack dev server or the npm build.
After hours of reverse-engineering ts-loader I finally found out what was causing this "freeze" (as it may seem) in my case:
I am building a web scraper and had amassed around 40Gb of cached data in a hashed directory structure between the previous, successful deployment and the now failing/freezing deployment.
Turned out, since I'd forgotten to include the root cache directory in the "exclude" option in my tsconfig.json, ts-loader was going through all sub-folders in the cache directory. So, it wasn't actually hanging, it was just looking through millions of files.
When I added the cache directory to the excluded files option, everything went back to normal.
Hope this helps you with your issue. In case you want to look into what's going on with typescript, I'd recommend to experiment with some console.logs in the visitDirectory-function in typescript.js. This was what finally helped me resolve this problem.
Cheers
Sam

Resources