I am using hapi-router npm module. Can not use hapi-router with typescript.
await server.register(
{
plugin: HapiRouter,
options: {
routes: "./src/api/**/routes.ts",
},
},
{ routes: { prefix: "/api/v1" } }
);
My route.ts file looks like this
import controller from "./controller";
import validator from "./validator";
export default [{
method: "GET",
path: "/products/{id}",
options: {
tags: ["api", "Products"],
description: "Get Product By ID",
validate: validator.byId
},
handler: controller.byId
}]
It gives me an error: "Can not use import statement outside a module"
Even when I use require statement it doesn't work.
Related
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..
I am using babel-plugin-content-transformer library to use yaml files. I need to use them instead of json in react-i18next localisation library. It works fine but there is one issue: when i change some translation in .yml file the changes displays only after I restart metro server. Reload also doesn't works, I see no changes after I pressed 'r' to reload server. To see changes I need to stop and after that run server again.
My babel.config.js is
module.exports = function (api) {
const presets = [['module:metro-react-native-babel-preset']]
const plugins = [
['module-resolver', {
root: ['./'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'#bluecentury': './src',
}
}],
['module:react-native-dotenv', {
'moduleName': '#vemasys/env',
}],
['react-native-reanimated/plugin'],
['content-transformer', {
transformers: [{
file: /\.ya?ml$/,
format: 'yaml'
}]
}]
]
api.cache(false)
return {
presets,
plugins
}
}
my i18n.ts is
import i18n from 'i18next'
import {initReactI18next} from 'react-i18next'
import translationEN from './enyaml.yml'
// import translationEN from './en.json'
const resources = {
en: {
translation: translationEN,
},
}
i18n.use(initReactI18next).init({
resources,
lng: 'en',
fallbackLng: 'en',
interpolation: {
escapeValue: false,
},
})
When I'm using en.json everything works fine.
I am trying to migrate my tests from jest to vitest. I have a test suite that uses the dotenv package to pull in my .env variables.
I have this in my test suite
beforeAll(async () => {
vi.clearAllMocks();
cleanUpMetadata();
dotenv.config();
controller = new UserController(container.get<UserServiceLocator>(Symbol.for("UserServiceLocator")),
container.get<EmailServiceLocator>(Symbol.for("EmailServiceLocator")));
});
and this is the code in the test that has the undefined variable
let requestObj = httpMocks.createRequest({
cookies: {
token: jwt.sign({ username: "testusername" }, process.env.JWT_SECRET_KEY!)
}
});
Is there something special to vitest that i have to do in order to get my .env variables to be accessible?
You can include the dotenv package(if thats what you are using) into the vitest.config.ts file, it will look something like this below:
import { defineConfig } from 'vitest/config';
import { resolve } from 'path';
export default defineConfig({
root: '.',
esbuild: {
tsconfigRaw: '{}',
},
test: {
clearMocks: true,
globals: true,
setupFiles: ['dotenv/config'] //this line,
},
resolve: {
alias: [{ find: '~', replacement: resolve(__dirname, 'src') }],
},
});
import.meta.env.%VARIABLE_NAME%
Got it from here: https://stackoverflow.com/a/70711231
Getting an error
[vite] Internal server error: Cannot read property 'length' of undefined
This is happening while trying to run my vue project using vite.
Below is the error stack:
Build failed with 1 error: node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59574:34: ERROR: [plugin: vite:dep-scan] Cannot read property 'length' of undefined 2:44:29 PM [vite] Internal server error: Cannot read property 'length' of undefined at matches (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59574:35) at /Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59633:58 at Array.find () at Context.resolveId (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59633:42) at Object.resolveId (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:36609:55) at processTicksAndRejections (internal/process/task_queues.js:95:5) at async ModuleGraph.resolveUrl (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:56244:26) at async ModuleGraph.getModuleByUrl (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:56124:23) at async doTransform (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:55582:20)
My vite.config.js
import { defineConfig } from 'vite';
import { createVuePlugin } from 'vite-plugin-vue2';
const config = require('./config');
const path = require('path');
export default defineConfig({
plugins: [createVuePlugin()],
server: {
port: 8080,
},
resolve: {
alias: [
{
'#': path.resolve(__dirname, './src'),
},
{
'#common': path.resolve(__dirname, '../common-v2'),
},
// {
// find: path.resolve(__dirname, '../static'),
// replacement: config.dev.assetsSubDirectory,
// ignore: ['.'],
// },
// {
// find: path.resolve(__dirname, '../firebase-messaging-sw.js'),
// replacement: 'firebase-messaging-sw.js',
// ignore: ['.'],
// },
],
},
build: {
chunkSizeWarningLimit: 600,
cssCodeSplit: false,
},
});
When I encountered this error, adding the following to vite.config.js seemed to resolve it.
resolve: {
alias: [
{
find: /^~(.*)$/,
replacement: 'node_modules/$1',
},
],
},
I had the same issue with a brand new Vite project. I don't know if this is your case, but I created this new project under a directory of another project like so:
/some/path/my-project <- "parent project"
/some/path/my-project/... <- other project files
/some/path/my-project/node_modules
/some/path/my-project/... <- other project files
/some/path/my-project/brand-new-vite-project <--- THIS ONE!
This nesting seems to generate the issue, because I moved the brand new project elsewhere and everything worked as expected.
Same problem encountered while getting throug Amplify "getting started" (which requires a new alias)
The solution for me was to rewrite the config as follows
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
"./runtimeConfig": "./runtimeConfig.browser",
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
],
},
});
I try do deploy me project to AWS Lambda with serverless-webpack. But i got error on import model to sequelize.
Here is error log from AWS:
module initialization error: ReferenceError
at t.default (/var/task/app.js:1:8411)
at Sequelize.import(/var/task/node_modules/sequelize/lib/sequelize.js:398:32)
My serverless.yml file:
service: backend-aquatru
plugins:
- serverless-webpack
- serverless-offline
- serverless-dotenv-plugin
custom:
webpackIncludeModules:
forceInclude:
- pg
- pg-hstore
webpackConfig: 'webpack.config.js'
includeModules: true
packager: 'npm'
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: us-west-1
functions:
app:
handler: app.handler
events:
- http: 'ANY /'
- http: 'ANY {proxy+}'
webpack.config.js
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
entry: './app.js',
target: 'node',
externals: [nodeExternals()],
output: {
libraryTarget: 'commonjs',
path: path.resolve(__dirname, '.webpack'),
filename: 'app.js', // this should match the first part of function handler in serverless.yml
},
plugins: [
new Dotenv(),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
include: __dirname,
loaders: ['babel-loader'],
},
],
},
}
And my sequelize import model:
import {sequelize as dbConfig} from '../config/vars'
import Sequelize from 'sequelize';
const db = {
Sequelize,
sequelize: new Sequelize(dbConfig.makeUri(), {
operatorsAliases: Sequelize.Op,
dialect: dbConfig.dialect
}),
};
// require each model from every endpoint with sequelize
db.User = db.sequelize.import('User', require('../api/models/user.model'));
// run associations from every model here
Object.keys(db).forEach((modelName) => {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
export const User = db.User;
export default db;
I saw serverless-webpack issue with import model files with require, and modify my code that way. But it doesn't help. Here is link to discussion. [enter link description here][issue]