How to deal with the problem of TS2367 error after the replacement code? - rollup

I use rollup-replace as the variable switch of the builder in the project, but I have encountered a problem when using it with TypeScript, and I always give me errors like this:
semantic error TS2367: This condition will always return'true' since the types'boolean' and'string' have no overlap.
I will write code like this in my code
// a.ts
import Prod from './prod';
import Pre from './pre';
If(process.env.PROD === ’true’){
console.log(‘is prod’);
Prod.init();
} else {
console.log(‘is pre’);
Pre.init();
}
// rollup.config.js
import typescript from 'rollup-plugin-typescript2';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import replace from '#rollup/plugin-replace';
export default [
{
input: 'src/a.ts',
output: { file: 'dist/a.js', format: 'iife' },
plugins: [
replace({ values: { 'process.env.PROD': JSON.stringify(true) }, preventAssignment: true }),
resolve({ browser: true }),
commonjs(),
typescript(),
]
}
]
In the above build code, replace needs to precede resolve, because it is necessary to use replace to avoid useless JS from being imported into the bundle file.
Who can help me solve this meaningless error message?

In the rollup document, I found the advanced usage of treeshake.moduleSideEffects, which talked about the ability I want to achieve.
import typescript from 'rollup-plugin-typescript2';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import replace from '#rollup/plugin-replace';
export default [
{
input: 'src/a.ts',
output: { file: 'dist/a.js', format: 'iife' },
plugins: [
replace({ values: { 'process.env.PROD': JSON.stringify(true) }, preventAssignment: true }),
resolve({ browser: true }),
commonjs(),
typescript(),
],
treeshake: {
moduleSideEffects: false, // Prune unused pure external imports
},
}
]

Related

"You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file". Electron+Vue

I am trying to use the npm package "Typeorm" in my Electron + Vue project, but when I run it I have this error:
Module parse failed: Unexpected character '​' (2:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import { EntitySchema } from "typeorm"
> ​
| export default new EntitySchema({
| name: "Post", // Will use table name `post` as default behaviour.
But I don't even have a webpack.config.js in my project. Not even inside files from frameworks that i'm using. So I can't follow the tips of this https://webpack.js.org/concepts#loaders.
The file that contains this import:
Category.js
import { EntitySchema } from "typeorm"
export default new EntitySchema({
name: "Category", // Will use table name `category` as default behaviour.
tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
columns: {
id: {
primary: true,
type: "int",
generated: true,
},
name: {
type: "varchar",
},
},
})
This is my Babel.config:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
To try to make it work, in my vue.config.js I added this "transpileDependecies", as suggested in #vue/cli-plugin-babel/preset . But it stills the same error.
vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: [
'typeorm'
],
configureWebpack: {
devtool: 'source-map',
},
pluginOptions: {
vuetify: {
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vuetify-loader
}
}
})
Other similar questions did not help..

ESM library generated with rollup-plugin-postcss throws Cannot find module '../node_modules/style-inject/dist/style-inject.es.js'

We are maintaining an internal library which is exporting ESM modules using Rollup. We have just recently switched to using CSS modules, which we have set with rollup-plugin-postcss. We want to inject these styles into the head rather than have an external file.
Our built bundle generates the ESM file with:
import styleInject from '../node_modules/style-inject/dist/style-inject.es.js';
Our consuming library then fails with
Uncaught Error: Cannot find module '../node_modules/style-inject/dist/style-inject.es.js'
I would expect the ESM export to import styleInject from 'style-inject' and style-inject to be included in the package-lock.json as a dependency. What is the correct way of using CSS Modules and injecting into the head for the consumer of a library?
rollup.config.js
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import babel from '#rollup/plugin-babel';
import json from '#rollup/plugin-json';
import postcss from 'rollup-plugin-postcss';
import pkg from './package.json';
import fg from 'fast-glob';
import path from 'path';
export default [
{
input: 'src/index.js',
external: external(),
output: [
{
name: '#my/packageName',
file: pkg.module,
format: 'es',
sourcemap: true,
},
],
plugins: [
{
name: 'watch-external',
async buildStart() {
const files = await fg(['src/index.d.ts', 'playground/**/*']);
for (let file of files) {
this.addWatchFile(path.resolve(file));
}
},
},
json(),
postcss({
modules: true,
}),
babel({
exclude: /node_modules/,
babelHelpers: 'runtime',
babelrc: false,
presets: [
[
'#babel/preset-env',
{
modules: false,
useBuiltIns: 'entry',
corejs: 3,
targets: {
ie: 11,
},
},
],
'#babel/preset-react',
],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-export-namespace-from',
],
}),
commonjs(),
],
},
];
function external() {
const { dependencies = {}, peerDependencies = {} } = pkg;
const externals = [
...Object.keys(dependencies),
...Object.keys(peerDependencies),
];
return id =>
// match 'lodash' and 'lodash/fp/isEqual' for example
externals.some(dep => id === dep || id.startsWith(`${dep}/`));
}
There is a bug in the library where the import is relative rather than being the module name.
There is an open pr, but the library looks like it is no longer being maintained. There are two recommended solutions in the comments:
String replace the built output
Add a custom rollup plugin to do this
This is not a bug at all. It works properly because stylesInject is just a function from 'styles-inject' package, so we can allow it to be bundled. But it is not bundled because most likely you have this setting in your rollup.config.js:
external: [
/node_modules/
]
So, replace it with a code bellow and it will work:
external: (id) => {
if (/style-inject/.test(id)) return false;
if (/node_modules/.test(id)) return true;
return false;
},
also, you can write a regexp for it instead
You need to do 2 things:
Add style-inject dependency in package.json
"dependencies": {
"style-inject": "^0.3.0"
},
Add following plugin to rollup.config.js
const plugins = [
...
{
/**
* - https://github.com/egoist/rollup-plugin-postcss/issues/381#issuecomment-880771065
* - https://lightrun.com/answers/egoist-rollup-plugin-postcss-esm-library-generated-with-rollup-plugin-postcss-throws-cannot-find-module-node_modulesstyle-in
*/
name: 'Custom Rollup Plugin`',
generateBundle: (options, bundle) => {
Object.entries(bundle).forEach((entry) => {
// early return if the file we're currently looking at doesn't need to be acted upon by this plugin
if (!entry[0].match(/.*(.scss.js)$/)) {
return;
}
// this line only runs for .scss.js files, which were generated by the postcss plugin.
// depending on the use-case, the relative path to style-inject might need to change
bundle[entry[0]].code = entry[1].code.replace(
/\.\.?\/[^\n"?:*<>|]+\/style-inject\/dist\/style-inject.es.js/g,
'style-inject',
);
});
},
}
];
References:
https://github.com/egoist/rollup-plugin-postcss/issues/381#issuecomment-880771065
https://lightrun.com/answers/egoist-rollup-plugin-postcss-esm-library-generated-with-rollup-plugin-postcss-throws-cannot-find-module-node_modulesstyle-in

NPM Module's CSS not applied using #vue/web-component-wrapper VueJS Webcomponents

While developing a Vue web component, using #vue/web-component-wrapper, the styles of npm_modules are not applied. The css actually isn't loaded at all.
Here is my main.js:
import Vue from 'vue';
import wrap from '#vue/web-component-wrapper';
import App from './App.vue';
import '#/modules/filters';
import '#fortawesome/fontawesome-free/css/all.css';
import '#fortawesome/fontawesome-free/js/all';
const wrappedElement = wrap(Vue, App);
window.customElements.define('hello-there', wrappedElement);
Before that, I had the problem, that even my normal css wasn't applied. I resolved this, by help of the answer of this question: Styling not applied to vue web component during development
Even those imported styles in main.js:
import '#fortawesome/fontawesome-free/css/all.css';
won't load at all.
First thought -> there is something wrong with the webpack css-loader/vue-style-loader
Here is my vue.config.js (using the workaround from the above mentioned question):
function enableShadowCss(config) {
const configs = [
config.module.rule('vue').use('vue-loader'),
config.module.rule('css').oneOf('vue-modules').use('vue-style-loader'),
config.module.rule('css').oneOf('vue').use('vue-style-loader'),
config.module.rule('css').oneOf('normal-modules').use('vue-style-loader'),
config.module.rule('css').oneOf('normal').use('vue-style-loader'),
config.module.rule('postcss').oneOf('vue-modules').use('vue-style-loader'),
config.module.rule('postcss').oneOf('vue').use('vue-style-loader'),
config.module.rule('postcss').oneOf('normal-modules').use('vue-style-loader'),
config.module.rule('postcss').oneOf('normal').use('vue-style-loader'),
config.module.rule('scss').oneOf('vue-modules').use('vue-style-loader'),
config.module.rule('scss').oneOf('vue').use('vue-style-loader'),
config.module.rule('scss').oneOf('normal-modules').use('vue-style-loader'),
config.module.rule('scss').oneOf('normal').use('vue-style-loader'),
config.module.rule('sass').oneOf('vue-modules').use('vue-style-loader'),
config.module.rule('sass').oneOf('vue').use('vue-style-loader'),
config.module.rule('sass').oneOf('normal-modules').use('vue-style-loader'),
config.module.rule('sass').oneOf('normal').use('vue-style-loader'),
config.module.rule('less').oneOf('vue-modules').use('vue-style-loader'),
config.module.rule('less').oneOf('vue').use('vue-style-loader'),
config.module.rule('less').oneOf('normal-modules').use('vue-style-loader'),
config.module.rule('less').oneOf('normal').use('vue-style-loader'),
config.module.rule('stylus').oneOf('vue-modules').use('vue-style-loader'),
config.module.rule('stylus').oneOf('vue').use('vue-style-loader'),
config.module.rule('stylus').oneOf('normal-modules').use('vue-style-loader'),
config.module.rule('stylus').oneOf('normal').use('vue-style-loader'),
];
configs.forEach((c) =>
c.tap((options) => {
options.shadowMode = true;
return options;
})
);
}
module.exports = {
chainWebpack: (config) => {
enableShadowCss(config);
},
configureWebpack: {
output: {
libraryExport: 'default',
},
resolve: {
symlinks: false,
},
module: {
rules: [
{
test: /\.ya?ml$/,
use: 'raw-loader',
sideEffects: true,
},
],
},
},
css: {
extract: false,
loaderOptions: {
sass: {
additionalData: `#import "#/styles/_variables.scss";`,
},
},
},
};
So I tried to add css-loader/vue-style-loader manually to webpack with:
chainWebpack: (config) => {
enableShadowCss(config);
config.module
.rule('css')
.test(/\.css$/)
.use('css-loader')
.loader('css-loader')
.end();
},
maybe those styles load now, but it throws an syntax error whilst building anyways:
./node_modules/#fortawesome/fontawesome-free/css/all.css
Syntax Error: CssSyntaxError
(1:4) /Users/.../node_modules/#fortawesome/fontawesome-free/css/all.css Unknown word
> 1 | // style-loader: Adds some css to the DOM by adding a <style> tag
| ^
2 |
3 | // load the styles
I know I know, seems obvious but those lines don't appear in the file at all. Maybe in an imported file though.
Without using the wc-wrapper everything works fine!!
Well anyways... no clue what I should try next. I am a newbie to webpack and Vue!
If anybody has an idea I would greatly appreciate it!
Cheers

How to create my own component library based on Vuetify

I want create my component library based on Vuetify and publish on npm.
Vuetify has already vue-plugin standard installation and use vuetify-loader, I think was a more complex scenario than plain HTML component.
For example, I want create my Login Form, my Article Page, my default calendar picker with preset values.
There's a standard way or guide to do this or a sample to do that?
I use last version of vuetify (2.0.7)
I just got it working for Vue3/Vuetify3. In a nutshell (using pnpm, vite, typescript, Vue plugin):
Create the component as a new project:
pnpm create vue#latest
-> your-plugin
-> Typescript
-> ESLint
cd <project>
echo auto-install-peers = true > .npmrc
pnpm add -D vuetify rollup-plugin-typescript2
Then remove all the components and make your own component instead.
Create src\components\index.ts and src\YourPlugin.ts
src\components\index.ts
export {default as YourComponent} from "./YourComponent.vue"
src\YourPlugin.ts
import type { App } from "vue"
import { YourComponent } from "./components"
export default {
install: (app: App) => {
app.component("YourComponent", YourComponent)
}
};
vite.config.ts
Add to the imports:
import vuetify from 'vite-plugin-vuetify'
import typeScript2 from "rollup-plugin-typescript2"
Add to the plugins:
vuetify({
autoImport: true,
}),
typeScript2({
check: false,
include: ["src/components/*.vue"],
tsconfigOverride: {
compilerOptions: {
sourceMap: true,
declaration: true,
declarationMap: true,
}
},
exclude: [
"vite.config.ts"
]
})
Add a new section build to the defineConfig:
build: {
cssCodeSplit: false,
lib: {
entry: "./src/YourPlugin.ts",
formats: ["es", "cjs"],
name: "CommonVtfyPlugin",
fileName: format => (format == "es" ? "index.js" : "index.cjs"),
},
rollupOptions: {
external: ["vue", "vuetify/lib"],
output: {
globals: {
vue: "Vue",
vuetify: "Vuetify",
'vuetify/components': 'VuetifyComponents',
'vuetify/directives': 'VuetifyDirectives'
}
}
}
},
dist\index.d.ts
I have not figured out how to generate this on yet. But this is a generic stand in:
declare const _default: any;
export default _default;
package.json
Add this:
"type": "module",
"exports": {
".": "./dist/index.js"
},
"types": "./dist/index.d.ts",
"files": [
"dist"
],
You can use it in any Vue project by importing it as a plugin:
import YourComponent from 'your-plugin'
app.use(YourComponent)
No guarantees on how optimized that is (feedback welcome).. but it works (tm)..
A more detailed answer can be found pnpm monorepo: how to set up a simple reusable (vue) component for reuse? (any updates will primarily be updated in that answer as well, if any)

Can't modifyVars dynamically in Less / Nuxt.Js

I'm building a web platform using Nuxt.Js and Ant as a front-end framework.
I saw that it is possible to change the theme of Ant using Less and Less-loader. So I did it before the build with the following code :
antd-ui.js
import Vue from 'vue'
import Antd from 'ant-design-vue/lib'
Vue.use(Antd)
nuxt.config.js
...
css: [
{
src: 'ant-design-vue/dist/antd.less',
lang: 'less'
}
],
...
build: {
transpile: [/^element-ui/],
loaders: {
less: {
javascriptEnabled: true,
modifyVars: {
// You can here change your Ant vars
}
},
},
...
So it works but now I want to implement a Dark Mode so I need to modify the vars dynamically through the code like this :
component.vue
<script>
import less from 'Less'
export default {
...
methods: {
changeTheme() {
less.modifyVars(
...
)
}
...
}
...
But I have the following message in the console :
Less has finished and no sheets were loaded
And nothing has changed... So if you can help me in any way, thanks in advance !