I have a monorepo:
domain/
entities/
account.ts
...
mobile/
src/
app.ts
node_modules/
package.json
babel.config.js
I want to set an alias so that app.ts can simply call:
import { Account } from 'domain/entities/account'
instead of
import { Account } from '../../../domain/entities/account'
I tried doing it like so:
const path = require('path')
module.exports = (api) => {
api.cache(true)
return {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
['module:react-native-dotenv', {
moduleName: 'react-native-dotenv'
}],
[
'module-resolver',
{
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx'
],
alias: {
domain: path.resolve(__dirname, '../domain')
}
}
]
]
}
}
But it doesn't work, unfortunately.
It throws:
Error: Unable to resolve module /home/kibe/work/iros-customer-frontend/domain/entities/account from ...
None of these files exist:
* ../domain/entities/account(.js|.jsx|.ts|.tsx)
How can I import stuff from outside the main directory?
Go to "domain" Folder and add a new file package.json with following content
{
"name": "domain"
}
Now you import like this
import { Account } from 'domain/entities/account'
Related
I am building a library using Vite/Vue3/Quasar and I would like to export a quasar-variables.sass file as it is written without it being compiled or anything. Just straight SASS file that I can import to my other projects.
Is this possible with Vite?
Here is my vite.config.js:
import { resolve } from 'path';
import { defineConfig } from 'vite';
import { quasar, transformAssetUrls } from '#quasar/vite-plugin';
import eslintPlugin from 'vite-plugin-eslint';
import vue from '#vitejs/plugin-vue';
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.js'),
name: 'AvvinueClowder',
fileName: (format) => `avvinue-clowder.${format}.js`,
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue',
},
},
},
},
plugins: [
vue({
template: { transformAssetUrls },
}),
eslintPlugin(),
quasar({
sassVariables: 'src/style/_quasar-variables.sass',
}),
],
resolve: {
alias: {
'#': resolve(__dirname, './src'),
},
},
});
And part of my package.json:
"version": "2.0.9",
"files": [
"dist"
],
"main": "./dist/avvinue-clowder.umd.js",
"module": "./dist/avvinue-clowder.es.js",
"exports": {
".": {
"import": "./dist/avvinue-clowder.es.js",
"require": "./dist/avvinue-clowder.umd.js"
}
},
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
And this is what gets spit out in the dist folder:
Right now everything gets converted to simple CSS and the variables seem to get lost, which is forcing me to declare multiple variable files in multiple repositories, instead of just importing it from my NPM library I'm creating.
Thank you!
For Vite specifically, its easier if you just create a /public folder in your root and add files/assets that shouldn't be altered by the build script.
You can use the rollup copy plugin to copy your file into dist folder
import copy from 'rollup-plugin-copy'
plugins: [
copy({
targets: [
{ src: 'src/style/_quasar-variables.sass', dest: 'dist/style' }
]
})
]
Another way, you can just add your file to npm by excluding it from .npmignore file
/src <- This line prevents uploading the whole src folder to npm
!src/style/_quasar-variables.sass <- This will add your file to npm package
I've succesfully added vite to my project. It builds fine for prodiction. However in Production I have an error
Uncaught ReferenceError: describe is not defined
at index.ba9d79ff.js:1119:1426
I then saw the my .spec files where being added. I thought vite would of handled the removal of the test files. I want to remove my .spec files from production.
but not having such luck. I'm using Vue 2 with vite. I added
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
but the files are still being added. Is there something more I need to do?
My config
import { defineConfig } from "vite";
import { createVuePlugin as vue } from "vite-plugin-vue2";
import { VuetifyResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
// https://vitejs.dev/config/const
const path = require("path");
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [
// Vuetify
VuetifyResolver(),
],
}),
],
resolve: {
extensions: [
".mjs",
".js",
".ts",
".jsx",
".tsx",
".json",
".vue",
".scss",
],
alias: {
"#": path.resolve(__dirname, "./src"),
json2csv: "json2csv/dist/json2csv.umd.js",
"~bootstrap": "bootstrap",
},
},
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
extensions: etc,
css: {
preprocessorOptions: {
scss: {
// additionalData: `#import "src/scss/app.scss";`,
// additionalData: `#import "src/scss/_variables.scss";`,
sourceMap: false,
additionalData(source, fp) {
// All scss files ending with imports.scss
// will not re-import additionalData
if (fp.endsWith("_variables.scss")) return source;
// Use additionalData from legacy nuxt scss options
// return `#import "#/assets/mixin.scss"; ${source}`;
return `#import "src/scss/_variables.scss"; ${source}`;
},
},
},
},
server: {
port: 8090,
},
});
I have a component library written in vue that I am wrapping up with rollup
I am having an issue with mixins not being wrapped up into the final library. Intially i thought that the path was the issue as most of the mixins are local.
Originally:
import mixin from '../../mixins/color'
Repo folder structure
- dist //output
- src //All files related to the actual component within the library
- components
- comps
- alert //general components
- inputs //input components
- layout //layout components /row/col
- mixins
- utilities
- entry.js //rollup points to this
- ... //I used nuxt to develop the components to focus on SSR so there are more folders but are excluded in the rollup process
Apparently native rollup doesn't like indirect imports so I attempted to add rollup-plugin-includepaths. My understanding is that I would need to mention the paths required in the imports to work correctly.
Therefore, I added rollup-plugin-includepaths to rollup.config.js plugins and added the root path and the output director as the options
includePaths({
paths: ['src/components/', 'src/mixins/', 'src/utilities/'],
extensions: ['.js', '.vue']
}),
**this did not work **
I decided to remove all relative imports and create aliases for each required directory. This did not work either
What is happening is all mixins imported into the component and added as mixin: [mixins] //whatever they may be are not included in the compiled product?!?!?!
What am I missing????
// rollup.config.js
import fs from 'fs'
import path from 'path'
import vue from 'rollup-plugin-vue'
import alias from '#rollup/plugin-alias'
import commonjs from '#rollup/plugin-commonjs'
import replace from '#rollup/plugin-replace'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import minimist from 'minimist'
import postcss from 'rollup-plugin-postcss'
import includePaths from 'rollup-plugin-includepaths'
import del from 'rollup-plugin-delete'
// Get browserslist config and remove ie from es build targets
const esbrowserslist = fs
.readFileSync('./.browserslistrc')
.toString()
.split('\n')
.filter(entry => entry && entry.substring(0, 2) !== 'ie')
const argv = minimist(process.argv.slice(2))
const projectRoot = path.resolve(__dirname)
const baseConfig = {
input: 'src/entry.js',
plugins: {
preVue: [
alias({
resolve: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
entries: [
{ find: '#', replacement: path.resolve(projectRoot, 'src') },
{
find: '#mixins',
replacement: path.resolve(projectRoot, 'src', 'mixins')
},
{
find: '#comps',
replacement: path.resolve(projectRoot, 'src', 'components', 'comps')
},
{
find: '#inputs',
replacement: path.resolve(
projectRoot,
'src',
'components',
'inputs'
)
},
{
find: '#utilities',
replacement: path.resolve(projectRoot, 'src', 'utilities')
}
]
}),
includePaths({
paths: ['src/components/', 'src/mixins/', 'src/utilities/'],
extensions: ['.js', '.vue']
}),
commonjs(),
postcss()
],
replace: {
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.ES_BUILD': JSON.stringify('false')
},
vue: {
css: false,
template: {
isProduction: true
}
},
babel: {
exclude: 'node_modules/**',
extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue']
}
}
}
// ESM/UMD/IIFE shared settings: externals
// Refer to https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
const external = [
// list external dependencies, exactly the way it is written in the import statement.
// eg. 'jquery'
'vue'
]
// UMD/IIFE shared settings: output.globals
// Refer to https://rollupjs.org/guide/en#output-globals for details
const globals = {
// Provide global variable names to replace your external imports
// eg. jquery: '$'
vue: 'Vue'
}
// Customize configs for individual targets
const buildFormats = []
if (!argv.format || argv.format === 'es') {
const esConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.esm.js',
format: 'esm',
exports: 'named'
},
plugins: [
del({ targets: 'dist/*' }),
replace({
...baseConfig.plugins.replace,
'process.env.ES_BUILD': JSON.stringify('true')
}),
...baseConfig.plugins.preVue,
vue(baseConfig.plugins.vue),
babel({
...baseConfig.plugins.babel,
presets: [
[
'#babel/preset-env',
{
targets: esbrowserslist
}
]
]
})
]
}
buildFormats.push(esConfig)
}
if (!argv.format || argv.format === 'cjs') {
const umdConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.ssr.js',
format: 'cjs',
name: 'Components',
exports: 'named',
globals
},
plugins: [
replace(baseConfig.plugins.replace),
...baseConfig.plugins.preVue,
vue({
...baseConfig.plugins.vue,
template: {
...baseConfig.plugins.vue.template,
optimizeSSR: true
}
}),
babel(baseConfig.plugins.babel)
]
}
buildFormats.push(umdConfig)
}
if (!argv.format || argv.format === 'iife') {
const unpkgConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.min.js',
format: 'iife',
name: 'Components',
exports: 'named',
globals
},
plugins: [
replace(baseConfig.plugins.replace),
...baseConfig.plugins.preVue,
vue(baseConfig.plugins.vue),
babel(baseConfig.plugins.babel),
terser({
output: {
ecma: 5
}
})
]
}
buildFormats.push(unpkgConfig)
}
// Export config
export default buildFormats
Update
I moved the imported components out of the mixin and added them directly to the component that included them and got the same result. Therefore, i really have no clue what needs to happen.
TL;DR
None of the child components are being included in the rolled up dist '.js' files
Sometimes it is hard to include what is relevant and the question above is guilty.
The problem is within the larger component I had imported the children lazily
ex:
components:{
comp: ()=>import('comp') ///Does not work
}
changed to your standard
import comp from 'comp'
components:{
comp
}
In webpack's config file I set 'node_modules' and 'src/js/libs' as folders, where webpack should look for modules. 'jquery-form-styler' is installed via npm and lives in 'node_modules', but according to first error, webpack tries to find module in 'src/js/modules'. Why?
ERROR in ./src/js/modules/forms.js
Module not found: Error: Can't resolve 'jquery-form-styler' in '/Users/ildar.meyker/Sites/html-taxnet/src/js/modules'
# ./src/js/modules/forms.js 5:0-28
# ./src/js/modules/app.js
# ./src/js/main.js
My webpack.config.js content:
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: {
main: './src/js/main.js',
metrics: './src/js/metrics.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'public/js')
},
resolve: {
modules: [path.resolve(__dirname, 'src/js/libs'), 'node_modules']
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
optimization: {
splitChunks: {
chunks: "all",
minSize: 0
}
}
};
My files structure:
/node_modules/
/src/
js/
libs/
modules/
app.js
...
forms.js
...
main.js
metrics.js
forms.js starts as:
import $ from 'jquery';
import 'jquery.maskedinput';
import 'jquery-validation/jquery.validate';
import 'jquery-validation/additional-methods';
import 'jquery-form-styler';
...
Where 'jquery' and 'jquery-form-styler' are located in 'node_modules', while other modules in 'src/js/libs'.
Looks like webpack's reference to 'src/js/modules' wasn't due to it's attempt to find module in that folder. An error happened, because package.json in 'jquery-form-styles' had an incorrent main attribute. 'jquery.formstyler.min.js' instead of './dist/jquery.formstyler.min.js'.
I have a project like this:
root/
webpack-config.js
app/
app.js
js/
dep.js
core/
module.js
Here is the webpack config file:
module.exports = {
entry: './app/app.js',
output: {
path: __dirname,
filename: "[name]-bundle.js"
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
resolve: {
modulesDirectories: ['core']
}
...
in app.js, I have:
import local_dep from './js/dep';
import myModule from 'module';
This works as expected with webpack 1.x, but the myModule module isn't resolved with webpack 2, I'm getting "Module not found: can't resolve 'module' in ... \app".
It seems the modulesDirectories entry is ignored and the base URL corresponds to the entry's folder.
What can I do to make modules resolve correctly with webpack 2 ?
from: http://moduscreate.com/webpack-2-tree-shaking-configuration/
In Webpack 2, resolvers from root, modulesDirectories, and fallback settings will merge into a single property – modules. Here is how we can resolve file and module locations in Webpack 2:
resolve: {
modules: [
path.resolve('./client'),
'node_modules'
]
},
You can specify a number of directories in modules, but make sure not to forget node_modules or npm package dependencies will fail to load.
So in your case what was before:
resolve: {
modulesDirectories: ['core']
}
now needs to be
resolve: {
modules: ['core'] // also 'node_modules'
}
Edit: As others have noted, for Webpack 2, something like this works:
{
resolve: {
extensions: ['.js', '.jsx'],
modules: ['node_modules', path.resolve(__dirname, 'core')]
},
}
For Webpack 1, I have a setup that has this entry:
config.resolve = {
// Allows us to include js and jsx files without specifying the extension
extensions: ['', '.jsx', '.js'],
root: [path.resolve('./core')]
};
Thanks to Christopher Davies I fixed the problem by adding:
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
resolve: {
root: ['./core']
}
I had to add resolveLoader line otherwise I was getting an error about babel-loader that could not be loaded.