Import to next.config.js - javascript

I want to import file to next.config.js.
import * as all from "./links/redirects.js";
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: false,
trailingSlash: true,
}
(I added only part of module.exports content)
but I got error
Cannot use import statement outside a module
so I added In file package.json I added "type": "module" and I got error:
Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
ReferenceError: module is not defined

Related

How to create Vite based Vue component library consumable via .mjs files?

I created a Vite based Vue library. This library should distribute a single component inside a .mjs file.
Library setup
I basically created a new Vue app via npm create vue, moved every dependency to dev dependencies and added this to the package.json
"files": [
"dist"
],
"exports": {
".": {
"import": "./dist/computedRenderer.mjs",
"require": "./dist/computedRenderer.umd.cjs"
}
},
After that I added the following to my vite.config.ts file
build: {
lib: {
name: "mylib",
fileName: "computedRenderer",
entry: resolve(__dirname, './src/myComp/index.ts'), // index file exporting my component
},
rollupOptions: {
external: ["vue"],
output: {
globals: {
vue: "Vue",
},
},
},
}
Building the project should generate you a computedRenderer.mjs in the dist directory ( as expected ).
File server for testing purposes
I created a small Node server serving the static .mjs file
import cors from "cors";
import express from "express";
const port = 3_000;
express()
.use(express.json())
.use(cors())
.use(express.static('./public')) // directory contains the generated .mjs file
.listen(port, () => {
console.log(`Listening on port ${port}`);
});
When running the server and calling
http://localhost:3000/computedRenderer.mjs
you should get the file content
How I consume the component
In my main project I try to import the component dynamically during runtime like so
<script setup lang="ts">
import { onMounted } from "vue";
onMounted(async () => {
const source = 'http://localhost:3000/computedRenderer.mjs'; // example url
const { ComputedRenderer } = await import(source);
// ...
});
</script>
Unfortunately I get the following warning
The above dynamic import cannot be analyzed by Vite. See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* #vite-ignore */ comment inside the import() call to suppress this warning.
and error
Uncaught (in promise) TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
Is my library setup wrong? Or how can I consume the component via url?
Please let me know if you need more information

Why not possible to use ES imports in vue.config.js file with VueJS?

Why aren't ES imports working in vue.config.js file?
In example:
import * as path from 'path';
import * as pjson from './package.json';
module.exports = {
configureWebpack: {
resolve: {
alias: {
'#': path.join(__dirname, '/src'), // Alias # to /src folder for ES/TS imports
},
},
},
pwa: {
name: pjson.title,
assetsVersion: pjson.version,
},
};
Getting error after running npm run lint command (which uses vue-cli-service):
\vue.config.js:1
import * as path from 'path';
SyntaxError: Unexpected token *
at Module._compile (internal/modules/cjs/loader.js:720:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Module.require (internal/modules/cjs/loader.js:6
Also import 'path'; is not working either (tried also other syntax variants):
import 'path';
^^^^^^
SyntaxError: Unexpected string
The reason I'm trying to refactor from const path = require('path'); syntax is to avoid this new linter error after ESLint plugins upgrade:
Require statement not part of import
statement. eslint(#typescript-eslint/no-var-requires)
But it seems I still need to append this on top of the file: /* eslint-disable #typescript-eslint/no-var-requires */
The file vue.config.js is loaded by #vue/cli-shared-utils/lib/module.js via CommonJS require. Because of that, it expects vue.config.js to be CommonJS, too.
There are a few schemes you could employ to overcome this built-in limitation such as using vue.config.js to
require('#babel/register');
then require another file like vue.config.mjs where your ESM-based code resides.
But given this is only a config file that usually doesn't have a lot of code, it may be better not to fight city hall and instead use CommonJS.

Error 'Missing: SyncTestZoneSpec' during karma test with angular 4

First thing first : my project is totally sane on branch /develop with test passing and all.
I created a branch to clean imports and use aliases instead of ../../../../ each time I have to access classes. I added it into tsconfig.json :
"baseUrl": "src",
"paths": {
"#app/*": [
"app/*"
],
"#core/*": [
"app/core/*"
],
"#common/*": [
"app/common/*"
],
"#models/*": [
"app/models/*"
],
"#env/*": [
"environments/*"
],
"#assets/*": [
"assets/*"
]
}
I just finished but when executing the test with simple npm run test which do something like thiis is think karma start ./karma.conf.js --log-level error I get this error :
HeadlessChrome 67.0.3396 (Windows 10.0.0) ERROR
Uncaught Error: Missing: SyncTestZoneSpec
at http://localhost:9876/_karma_webpack_/vendor.bundle.js:270128
All I have changed is what I told above, what is this error telling me ?
EDIT : Correction with github links
Corrected this issue by updating the zone.js version to 0.8.26 and replaced the imports in test.ts by only one line :
import 'zone.js/dist/zone-testing';
But now I get this error for all tests :
HeadlessChrome 67.0.3396 (Windows 10.0.0) SomeService #getCurrentUser should return user object FAILED
TypeError: Cannot read property 'assertPresent' of undefined
at resetFakeAsyncZone node_modules/#angular/core/#angular/core/testing.es5.js:308:1)
at Object.<anonymous> node_modules/#angular/core/#angular/core/testing.es5.js:1015:1)
at ZoneQueueRunner.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.jasmine.QueueRunner.ZoneQueueRunner.execute node_modules/zone.js/dist/zone-testing.js:437:1)
HeadlessChrome 67.0.3396 (Windows 10.0.0): Executed 120 of 120 (120 FAILED) ERROR (4.725 secs / 4.633 secs)
Relatedd issue on github but no solution for now.
The content of my test.ts :
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import { getTestBed } from '#angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '#angular/platform-browser-dynamic/testing';
import 'zone.js/dist/zone-testing';
// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare const __karma__: any;
declare const require: any;
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();
Try moving the zone-testing import up to be one of the first imports like this:
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '#angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from
'#angular/platform-browser-dynamic/testing';
Taken from this bug report: All tests failed if order of imports is changed in test.ts

How to import/use Reflect in typescript

I'm trying to use the code in this SO answer. It uses Reflect. Here's a copy:
export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
annotation[key] = parentAnnotation[key];
}
});
var metadata = new ComponentMetadata(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
}
}
First, I got these two errors:
Property 'getMetadata' does not exist on type 'typeof Reflect'.
Property 'defineMetadata' does not exist on type 'typeof Reflect'.
Then I ran npm install reflect-metadata, but I don't know how to use it.
import { Reflect } from reflect-metadata;
Module '".../node_modules/reflect-metadata/index"' has no exported
member 'Reflect'.
Or
import { Reflect } from 'reflect-metadata/Reflect';
Cannot find name 'Record'.
Type '{}' is not assignable to type 'V'.
File '.../node_modules/reflect-metadata/Reflect.ts' is not a module.
Or
import "reflect-metadata"
rollup: Treating 'fs' as external dependency
bundle update failed: Error transforming .../node_modules/typescript/lib/typescript.js
with 'commonjs' plugin: The keyword 'package' is reserved (57066:28) in
.../node_modules/typescript/lib/typescript.js
Or
var reflect = require("reflect-metadata");
Cannot find name 'require'.
Or
declare var require: any;
var reflect = require("reflect-metadata");
var Reflect = reflect.Reflect;
rollup: Treating 'fs' as external dependency
bundle update failed: Error transforming .../node_modules/typescript/lib/typescript.js
with 'commonjs' plugin: The keyword 'package' is reserved (57066:28) in
.../node_modules/typescript/lib/typescript.js
Surely I'm just missing something silly, even a typo. What can I do to use this code?
you have to import the type declarations together with the (js) library
npm install reflect-metadata -D
inside your .ts file:
import "reflect-metadata";
As of today, #types/reflect-metadata is deprecated since reflect-metadata includes already its own typings.
So, to use them you just need to import the library (Uses the global scope). That's it.
Install it:
npm install reflect-metadata --save
Import it:
import 'reflect-metadata';
Typescript uses a Module loading paradigm that's a bit different than that of JavaScript.
Say you have a module Modulus that defines three classes A, B and C.
import { A } from "Modulus"
will import the class (or function) A from the module Modulus and make it available in your current module. If Typescript finds no export named A in Modulus and error will be thrown.
// Equivalent to the following in JavaScript:
// var ModuleNameOfYourChoice = require("Modulus")
import * as ModuleNameOfYourChoice from "Modulus"
will import all the exports declared within Modulus and make them available to the current module under the name ModuleNameOfYourChoice.
For your code, you need all the exports defined in reflect-metadata module and thus need to import it as
import * as Reflect from "reflect-metadata"
All the best!
Typescript documentation: http://www.typescriptlang.org/docs/handbook/modules.html#import
I found another solution if you can use es7+. So in your tsconfig.json file you need to change only one line. Change assigment of "target" to at least es2017. And that's all now you can use Reflect out of the box. I think it is very good solution because you do not have to care about additional dependencies
Example tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"outDir": "../dist",
"module": "umd",
"target": "es2017",
"sourceMap": true,
"noImplicitAny": true,
"strictNullChecks": true,
"removeComments": false,
"moduleResolution": "node"
},
"exclude": [
"node_modules",
"bower_components",
"dist"
]
}

TypeScript & SystemJS: angular ui router module not registered in transpiled js

I'm writing an AngularJS app, with TypeScript as a transpiler and SystemJS for module loading. I'm trying to load the angular-ui-router module to configure the routing, but fail to do so. I get this error:
angular.js:38 Uncaught Error: [$injector:modulerr]
This is the script:
import * as angular from "angular";
import * as router from "angular-ui-router";
const app: angular.IModule = angular.module("my.website", ["ui.router"]);
app.config((stateProvider: router.IStateProvider) => {
...
});
This is how the script is transpiled:
System.register(["angular"], function(exports_1, context_1) {
...
As you can see, the angular-ui-router is not registered, and hence the module is not loaded. Why? What am I doing wrong?
For completeness:
this is the SystemJS config:
System.config({
defaultJSExtensions: true,
map: {
"angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js",
"angular-ui-router": "https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"
}
});
These are the relevant TypeScript settings:
"target": "es5",
"module": "system"
I have loaded the TypeScript definition files using typings.
Transpilation is done by gulp-typescript.
Any clues?
I managed to get it working by importing both the file and the module. Ugly as it may be, this works:
import * as angular from "angular";
import "angular-ui-router";
import * as router from "angular-ui-router";
const app: angular.IModule = angular.module("my.website", ["ui.router"]);
app.config((stateProvider: router.IStateProvider) => {
...
});

Categories

Resources