I am not really strong with setting up my custom npm packages, therefore I am asking for help. I am trying to test my custom ESLint plugin rules on another project. For this, I have set up two projects in one root directory and linked them, using the file linking option (find the image of the file structure attached):
"eslint-plugin-winniepukki-guidelines": "file:../guide"
.eslintrc configuration file on the project, where I want to use my custom ESLint plugin:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'winniepukki-guidelines',
],
rules: {
'winniepukki-guidelines/use-license': 'error',
'winniepukki-guidelines/avoid-names': 'error',
},
};
Unfortunately, the rules do not apply properly with the following error:
Definition for rule 'winniepukki-guidelines/avoid-names' was not found.eslint(winniepukki-guidelines/avoid-names). This is how the avoid-names.js file looks like:
module.exports = {
meta: {
messages: {
avoidName: "Avoid using variables named '{{ name }}'"
}
},
create(context) {
return {
Identifier(node) {
if (node.name === "foo") {
context.report({
node,
messageId: "avoidName",
data: {
name: "foo",
}
});
}
}
};
}
};
And this is the ESLint package's index.js file itself, illustrating how do I export them:
const path = require('path');
const requireIndex = require('requireindex');
module.exports.rules = requireIndex(path.join(__dirname, 'rules'));
Project overview: https://i.stack.imgur.com/hLKcH.png
Related
I'm trying to use a package: quoters
this is app.svelte file. the same code works fine for react and other places in JS.
<script>
import Quote from "quoters";
let quote = "";
let category = "QUOTE";
function handleCategory() {
quote = new Quote(category).get();
}
</script>
when I am trying to run the code. i get the following error: "Uncaught ReferenceError: exports is not defined". I checked the line it is referencing to.
it contains definition for exports inside the quoters package.
Object.defineProperty(exports, "__esModule", { value: true });
I've tried everything like babel and commonjs. maybe i am missing something. please can anyone tell me what is the issue and also fix for this issue.
my rollup config file for reference:
import svelte from "rollup-plugin-svelte";
import commonjs from "#rollup/plugin-commonjs";
import resolve from "#rollup/plugin-node-resolve";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
import css from "rollup-plugin-css-only";
import copy from "rollup-plugin-copy";
import json from "#rollup/plugin-json";
import builtins from "rollup-plugin-node-builtins";
import globals from "rollup-plugin-node-globals";
import replace from "#rollup/plugin-replace";
import babel from "#rollup/plugin-babel";
import nodePolyfills from "rollup-plugin-node-polyfills";
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "public/build/bundle.js",
exports: "auto",
},
moduleContext: {
"node_modules/quoters/dist/parseData.js": "window",
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production,
},
}),
nodePolyfills(),
json(),
copy({
targets: [
{
src: "node_modules/bootstrap/dist/**/*",
dest: "public/vendor/bootstrap",
},
],
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: "bundle.css" }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
babel({
exclude: "node_modules/**", // only transpile our source code
}),
resolve({
dedupe: ["svelte"],
browser: true,
preferBuiltins: false,
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
};
I am attempting to load a .js file into my markdown file in React using gatsby-plugin-mdx. However, I am running into an import error, which shows as a WARN as follows:
warn ./.cache/caches/gatsby-plugin-mdx/mdx-scopes-dir/7cd2ab5f9fe4b662b5bb93052ee9e
f2c.js
Attempted import error: 'Test2' is not exported from '../../../../src/pages/test2'
(imported as 'Test2').
Looking at the cache, it seems benign enough:
import { Test2 } from "../../../../src/pages/test2";
import * as React from 'react';
export default {
Test2,
React
};
The contents of the import seem arbitrary, and the warn will be the same (and contents will not load). I used a simple export default function returning a h1 tag to experiment, for example.
My .md file is fairly straight forward:
# Testing 1
top
import { Test2 } from "../pages/test2"
<Test2 />
bottom
I suspected this is a configuration issue, but I'm yet to resolve it in my gatsby-config.js, which is currently as the following:
module.exports = {
siteMetadata: {
title: 'Marco Sousa Blog',
author: 'Marco Sousa'
},
plugins: [
'gatsby-plugin-dark-mode',
'gatsby-plugin-react-helmet',
'gatsby-plugin-sass',
'gatsby-plugin-sharp',
{
resolve: 'gatsby-source-filesystem',
options: {
name:'src',
path: `${__dirname}/src/`
}
},
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
'gatsby-remark-relative-images',
{
resolve: 'gatsby-remark-images',
options: {
maxWidth: 750,
linkImagesToOriginal: false
}
},
{
resolve: `gatsby-remark-katex`,
options: {
// Add any KaTeX options from https://github.com/KaTeX/KaTeX/blob/master/docs/options.md here
//strict: `ignore`,
}
},
{
resolve: `gatsby-remark-prismjs`,
options: {
classPrefix: "language-",
inlineCodeMarker: null,
aliases: {},
showLineNumbers: true,
noInlineHighlight: false,
languageExtensions: [
{
language: "superscript",
extend: "javascript",
definition: {
superscript_types: /(SuperType)/,
},
insertBefore: {
function: {
superscript_keywords: /(superif|superelse)/,
},
},
},
],
prompt: {
user: "root",
host: "localhost",
global: false,
},
// By default the HTML entities <>&'" are escaped.
// Add additional HTML escapes by providing a mapping
// of HTML entities and their escape value IE: { '}': '{' }
escapeEntities: {},
}
},
]
}
},
{
resolve: "gatsby-plugin-page-creator",
options: {
path: `${__dirname}/src/`,
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.mdx`, `.md`],
},
},
],
}
I think my querying/slug usage is fine, as the site and posts are operable prior (and after) to attempting to implement mdx. Observing the gatsby-plugin-mdx docs, I attempted to use gatsbyRemarkPlugins to encapsulate the other plugins, but this did not change the warn. What, more exactly, do you think could be the problem with my mdx usage?
This issue was in the way I imported. I simply changed
import { Test2 } from "../pages/test2"
<Test2 />
to
import Test2 from "../pages/test2"
<Test2 />
Test2.js was not a named export/import as I had imagined. Rather
Test2.js used the default export, which does not need to be wrapped with curly braces.
I am using craco and trying to figure out how to configure jsx. I keep getting the following error
Support for the experimental syntax 'jsx' isn't currently enabled (4:17):
They suggest that I add `babel/preset-react or use #babel/plugin-syntax-jsx to the plugin section to enable parsing but I'm unsure how to do that.
To clarify, I am trying to use a src folder outside the root of my react-app
craco.config.js
module.exports = {
webpack: {
alias: {},
plugins: {
add: [] /* An array of plugins */,
remove:
[] /* An array of plugin constructor's names (i.e. "StyleLintPlugin", "ESLintWebpackPlugin" ) */,
},
configure: {
/* Any webpack configuration options: https://webpack.js.org/configuration */
},
configure: (webpackConfig, { env, paths }) => {
console.log("WEBPACK");
console.log(webpackConfig);
webpackConfig.entry =
"C:\\Users\\danie\\Desktop\\Code\\JS\\npm_packages\\source\\src\\index.js";
return webpackConfig;
},
},
babel: {
presets: [],
plugins: [],
loaderOptions: (babelLoaderOptions, { env, paths }) => {
console.log("BABEL");
console.log(babelLoaderOptions);
return babelLoaderOptions;
},
},
};
Figured out my issue by adding the preset to my config file
craco.config.js
babel: {
presets: ['#babel/preset-react'],
// plugins: [],
loaderOptions: (babelLoaderOptions, { env, paths }) => {
console.log("BABEL");
console.log(babelLoaderOptions);
return babelLoaderOptions;
},
},
Vue Cli defaults to file-loader for SVG assets, but I want to use svg-sprite-loader (as well as a few others) instead.
I updated the vue.config.js file to do this and it still seems to use file-loader. Almost as though it's not picking up my config at all.
vue.config.js
module.exports = {
configureWebpack: {
module: {
rules: [
{
test: /\.(svg)(\?.*)?$/,
use: [
{
loader: 'svg-sprite-loader',
options: {
name: '[name]-[hash:7]',
prefixize: true
}
},
'svg-fill-loader',
'svgo-loader'
]
}
]
}
}
}
Is there anything wrong with my setup?
I'm still getting SVG files imported into my component as a URL string / path when it should be an object with properties.
Many thanks.
This took me a while to find a work around. Basically you need to stop file-loader matching on .svg. The best way I have found to do this is using chainWebpack and returning false from the test method on file-loader. I have included my working config.
module.exports = {
lintOnSave: false,
configureWebpack: {
module: {
rules: [
{
test: /\.(svg)(\?.*)?$/,
use: [
{
loader: 'svg-inline-loader',
options: {
limit: 10000,
name: 'assets/img/[name].[hash:7].[ext]'
}
}
]
}
]
}
},
chainWebpack: config => {
config.module
.rule('svg')
.test(() => false)
.use('file-loader')
}
}
The Webpack docs for Vue CLI 3.0 beta got updated with an example on how to replace an existing Base Loader. For svg-sprite-loader this means that you'll have to add the following configuration to your vue.config.js:
chainWebpack: config => {
config.module
.rule('svg')
.use('file-loader')
.loader('svg-sprite-loader')
}
I'm using Vue CLI 3.0.3 and this config works for me 😉
const path = require('path');
const glob = require('glob');
const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
module.exports = {
lintOnSave: false,
configureWebpack: {
plugins: [
new SpriteLoaderPlugin()
]
},
chainWebpack: config => {
config.module.rules.delete('svg');
config
.entry('app')
.clear()
.add(path.resolve(__dirname, './src/main.ts'))
config
.entry('sprite')
.add(...glob.sync(path.resolve(__dirname, `./src/assets/icons/*.svg`)));
config.module.rule('svg')
.test(/\.(svg)(\?.*)?$/)
.use('file-loader')
.loader('svg-sprite-loader')
.options({
extract: true,
spriteFilename: 'icons.svg'
})
}
};
Vue CLI docs for version 3.x in webpack section suggests to use something like this:
// vue.config.js
module.exports = {
chainWebpack: config => {
const svgRule = config.module.rule('svg')
// clear all existing loaders.
// if you don't do this, the loader below will be appended to
// existing loaders of the rule.
svgRule.uses.clear()
// add replacement loader(s)
svgRule
.use('vue-svg-loader')
.loader('vue-svg-loader')
}
}
Even vue-svg-loader configuration guide suggests same approach.
module.exports = {
chainWebpack: config => {
const svgRule = config.module.rule('svg')
svgRule.clear()
svgRule
.use('vue-svg-loader')
.loader('vue-svg-loader')
}
}
My goal is to let a webpack project be setup through node command crateEntireWepbackProject.js file.
I want to execute commands on the shell from a js file, so I can let them run automatically and later on also include custom specifications for a project.
The js file is not from within webpack, but has the commands to create a wepback project from scratch and makes the installs etc. just by me typing node createEntireWebpackProject.js
You do not need to write it from scratch. The best practice is using yeoman. There are a lot of generators with webpack. For example:
const Generator = require('yeoman-generator');
const mkdirp = require('mkdirp');
const path = require('path');
module.exports = class extends Generator {
prompting() {
this.log('Welcome to the classy example generator!');
const prompts = [
{
type: 'input',
name: 'name',
message: 'Name?',
default: this.appname,
}];
return this.prompt(prompts).then((props) => {
this.props = props;
});
}
default() {
if (path.basename(this.destinationPath()) !== this.props.name) {
this.log(
`Your application must be inside a folder named ${this.props.name}`);
this.log('I\'ll automatically create this folder.');
mkdirp(this.props.name);
this.destinationRoot(this.destinationPath(this.props.name));
}
}
writing() {
this.createPackageJson();
this.copyFiles();
this.fillTemplates();
this.makeCommands();
}
install() {
this.npmInstall(['bunyan', 'dotenv-safe'], { save: true });
this.npmInstall(['eslint', 'eslint-config-airbnb-base', 'eslint-plugin-import', 'jest'], { 'save-dev': true });
}
createPackageJson() {
this.fs.extendJSON('package.json', {
name: this.props.name,
version: '0.1.0',
main: 'src/app.js',
scripts: {
cs: 'eslint src/* __tests__/*',
'cs:fix': 'eslint src/* __tests__/* --fix',
start: 'node src/app.js',
test: 'npm run cs && jest',
},
dependencies: {},
devDependencies: {},
engines: {
node: '^8.1.0',
},
private: true,
jest: {
testEnvironment: 'node',
transform: {},
collectCoverage: true,
},
});
}
copyFiles() {
[
'.dockerignore',
'.eslintrc.json',
'src/app.js',
].forEach(name => this.fs.copy(this.templatePath(name), this.destinationPath(name)));
}
fillTemplates() {
this.fs.copyTpl(
this.templatePath('README.md'),
this.destinationPath('README.md'),
{
name: this.props.name,
});
}
makeCommands() {
this.spawnCommandSync('git' ['init']);
this.spawnCommandSync('git', ['add', '.']);
this.spawnCommandSync('git', ['commit', '-am', '"yo scaffolded app"']);
}
};