Vite not resolving file path when passed into function - flutter

I am using Vite to bundle an application, and in the index.html of one of my subpages, I have a function as follows:
var scriptTag = document.createElement("script");
scriptTag.src = "main.dart.js"; // change to app
scriptTag.type = "application/javascript"; // change to app
document.body.append(scriptTag);
Which gives the following error in the web console:
http://localhost:5000/app/main.dart.js net::ERR_ABORTED 404 (Not Found)
n # app.e9ec45f4.js:1
(anonymous) # app.e9ec45f4.js:1
setTimeout (async)
(anonymous) # app.e9ec45f4.js:1
load (async)
(anonymous) # app.e9ec45f4.js:1
Vite is not resolving this paths. I am assuming this is because Vite recognizes them as string inputs to a function and not a reference to a file. Is there any way to get Vite to resolve paths that are used in non-import functions?
Below are the relevant files in my directory structure:
src:
- index.html
- app:
- index.html
- main.dart.js
Here is my vite.config.js:
export default defineConfig({
root: "src",
publicDir: "../public",
build: {
emptyOutDir: true,
outDir: "../dist/web",
rollupOptions: {
input: {
main: "src/index.html",
app: "src/app/index.html",
},
external: ["assets", "splash/style.css"],
},
// optimizeDeps: {
// exclude: ["app/flutter_service_worker.js"],
// },
},
resolve: {
alias: {
vue: "vue/dist/vue.esm-bundler.js",
},
},
define: {
"process.env": process.env,
},
plugins: [
VitePWA({
strategies: "injectManifest",
srcDir: "app",
filename: "flutter_service_worker.js",
injectRegister: "null",
}),
],
});
Thanks

Related

ReferenceError: Cannot access 'getRenderingRef' before initialization at stencilSubscription$1

I'm using stenciljs to build my project via prerendering. However, the hydration happens below error.
package.json
"build": "stencil build --prerender --config stencil.config.ts",
output
[ ERROR ] Hydrate Error
ReferenceError: Cannot access 'getRenderingRef' before initialization at stencilSubscription$1
(C:\Users\aleung\Desktop\project\dist\hydrate\index.js:4996:5) at createStore$2
(C:\Users\aleung\Desktop\project\dist\hydrate\index.js:5138:13) at createRouter
(C:\Users\aleung\Desktop\project\dist\hydrate\index.js:5148:42) at hydrateAppClosure
(C:\Users\aleung\Desktop\project\dist\hydrate\index.js:5529:1) at hydrateFactory
(C:\Users\aleung\Desktop\project\dist\hydrate\index.js:34029:3) at render
(C:\Users\aleung\Desktop\project\dist\hydrate\index.js:34296:9) at
C:\Users\aleung\Desktop\project\dist\hydrate\index.js:34228:62 at new Promise (<anonymous>) at
Object.hydrateDocument (C:\Users\aleung\Desktop\project\dist\hydrate\index.js:34220:33) at prerenderWorker
(C:\Users\aleung\Desktop\project\node_modules\#stencil\core\compiler\stencil.js:9988:46)
stencil.config.ts
import { Config } from '#stencil/core';
import nodePolyfills from 'rollup-plugin-node-polyfills';
export const config: Config = {
namespace: 'project',
globalStyle: 'src/global/app.css',
globalScript: 'src/global/app.ts',
taskQueue: 'async',
outputTargets: [
{
type: 'www',
// comment the following line to disable service workers in production
serviceWorker: null,
baseUrl: 'https://myapp.local/',
},
],
plugins: [],
rollupPlugins: {
after: [nodePolyfills()],
},
devServer: {
reloadStrategy: 'pageReload',
openBrowser: false,
},
};
I expect the hydrate can be generated.
According to the docs, your output target needs a prerenderConfig property:
outputTargets: [
{
type: 'www',
// comment the following line to disable service workers in production
serviceWorker: null,
baseUrl: 'https://myapp.local/',
prerenderConfig: './prerender.config.ts'
},
],
And that file needs to export a PrerenderConfig not Config:
import { PrerenderConfig } from '#stencil/core';
export const config: PrerenderConfig = {
...
};
See https://stenciljs.com/docs/prerender-config

Set static path for karma runner

I was able prepare my OpenUI5 app for testing. I am having issue with the working directory for tests, because for my test I need to use a pre-populated sqlite3 database. For testing I use chrome with parameters --user-data-dir="C:\tmp" --profile-directory="karma", and I can place this file into chrome profile path. But I am not able to do this with karma, because karma always start with randomly generated id in path (karma-xxxxxx).
I am trying run custom browser config, with above chrome parameters, but it does not work.
module.exports = function(config) {
"use strict";
var chromeFlags = [
"--window-size=1280,1024",
"--disable-web-security",
"--allow-file-access-from-files",
'--user-data-dir="C:\\tmp"',
'--profile-directory="karma"'
];
config.set({
basePath: '',
ui5: {
type: "application",
preload: 'async',
animation: 'false',
paths: {
webapp: "www", // application
}
},
frameworks: ["ui5"],
browsers: ["CustomChrome"],
browserConsoleLogOptions: {
level: "error"
},
customLaunchers: {
CustomChrome: {
base: "Chrome",
flags: chromeFlags
},
CustomChromeHeadless: {
base: "ChromeHeadless",
flags: chromeFlags
}
},
});
};
with this config, chrome always start like this, so automatic testing does not work:

How to set up rollup with karma and babel?

I try to set up rollup with karma and babel for test.
I face two problems.
First, it cause error Uncaught TypeError about default.
Uncaught TypeError: Cannot use 'in' operator to search for 'default' in undefined
Second, it doesn't find external dependency.
Treating 'chai' as external dependency
What's wrong in my settings?
rollup conf
import babel from "rollup-plugin-babel";
import babelrc from "babelrc-rollup";
import istanbul from "rollup-plugin-istanbul";
import nodeResolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import builtins from "rollup-plugin-node-builtins";
import globals from "rollup-plugin-node-globals";
// import uglify from 'rollup-plugin-uglify'
let pkg = require('./package.json');
let external = Object.keys(pkg.dependencies);
export default {
entry: 'src/index.js',
plugins: [
babel(babelrc()),
istanbul({
exclude: ['test/**/*', 'node_modules/**/*']
}),
globals(),
builtins(),
nodeResolve({
module: true,
jsnext: true,
main: true,
browser: true,
extensions: ['.js']
}),
commonjs({
include: 'node_modules/**'
}),
//uglify(),
],
external: external,
targets: [
{
dest: pkg.main,
format: 'umd',
moduleName: 'sketchbook',
sourceMap: true
},
{
dest: pkg.module,
format: 'es',
sourceMap: true
}
]
};
karma conf
module.exports = function (config) {
config.set({
files: [
// Watch src files for changes but
// don't load them into the browser.
{pattern: 'src/**/*.js', included: false},
'test/**/*.spec.js',
],
browsers: ['Chrome'],
preprocessors: {
'src/**/*.js': ['rollup'],
'test/**/*.spec.js': ['rollup'],
},
rollupPreprocessor: {
plugins: [
require('rollup-plugin-buble')(),
],
format: 'umd', // Helps prevent naming collisions.
moduleName: 'sketchbook', // Required for 'iife' format.
sourceMap: 'inline', // Sensible for testing.
},
customPreprocessors: {
// Clones the base preprocessor, but overwrites
// its options with those defined below.
rollupBabel: {
base: 'rollup',
options: {
// In this case, to use
// a different transpiler:
plugins: [
require('rollup-plugin-babel')(),
],
}
}
}
// frameworks: ['mocha'],
// client: {
// mocha: {
// opts: 'test/mocha.opts'
//
// // // change Karma's debug.html to the mocha web reporter
// // reporter: 'html',
// //
// // // require specific files after Mocha is initialized
// // require: [require.resolve('bdd-lazy-var/bdd_lazy_var_global')],
// //
// // // custom ui, defined in required file above
// // ui: 'bdd-lazy-var/global',
// }
// }
});
};
source

SystemJS and KarmaJS: TypeError: System.import is not a function

I am trying to get my project working with Karma and SystemJS. I am using the karma-systemjs plugin with karma.
I keep getting the error below about System.import.
I believe it is because SystemJS is not being loaded by the time the karma-systemjs plugin runs. Please tell me what I am doing wrong.
Project structure
SystemJS configuration (system.conf.js)
System.config({
baseUrl: '',
defaultJSExtensions: true,
map: {
'jquery': 'vendor/kendo/js/jquery.min.js',
'angular': 'vendor/kendo/js/angular.js',
'kendo': 'vendor/kendo/js/kendo.all.min.js',
'angular-mocks': 'vendor/bower_components/angular-mocks/angular-mocks.js',
'angular-ui-router': 'vendor/bower_components/angular-ui-router/release/angular-ui-router.min.js',
'angular-toastr': 'vendor/bower_components/angular-toastr/dist/angular-toastr.tpls.min.js',
'angular-local-storage': 'vendor/bower_components/angular-local-storage/dist/angular-local-storage.min.js'
},
paths: {
'systemjs': 'vendor/bower_components/system.js/dist/system.js',
'system-polyfills': 'vendor/bower_components/system.js/dist/system-polyfills.js'
},
meta: {
'vendor/kendo/js/jquery.min.js': {
format: 'global',
exports: '$'
},
'vendor/kendo/js/angular.js': {
format: 'global',
deps: [
'vendor/kendo/js/jquery.min.js'
],
exports: 'angular'
},
'vendor/kendo/js/kendo.all.min.js': {
format: 'global',
deps: [
'vendor/kendo/js/angular.js'
],
exports: 'kendo'
},
'vendor/bower_components/angular-ui-router/release/angular-ui-router.min.js': {
format: 'global',
deps: [
'vendor/kendo/js/angular.js'
]
},
'vendor/bower_components/angular-mocks/angular-mocks.js': {
format: 'global',
deps: [
'vendor/kendo/js/angular.js'
],
exports: 'angular.mock'
},
'vendor/bower_components/angular-toastr/dist/angular-toastr.tpls.min.js': {
format: 'global',
deps: [
'vendor/kendo/js/angular.js'
]
},
'vendor/bower_components/angular-local-storage/dist/angular-local-storage.min': {
format: 'global',
deps: [
'vendor/kendo/js/angular.js'
]
}
}
});
Promise.all([
System.import('kendo'),
System.import('angular-mocks'),
System.import('angular-ui-router'),
System.import('angular-toastr'),
System.import('angular-local-storage')
]).then(function () {
System.import('angular')
.then(function (angular) {
System.import('ng/app/app.module')
.then(function (app) {
angular.bootstrap(document, ['s9.app']);
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
});
//# sourceMappingURL=system.conf.js.map
karma.conf.js
// Karma configuration
var configure = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '.',
transpiler: null,
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['systemjs', 'jasmine'],
systemjs: {
// Path to your SystemJS configuration file
configFile: 'system.conf.js',
// Patterns for files that you want Karma to make available, but not loaded until a module
// requests them. eg. Third-party libraries.
serveFiles: [
'vendor/kendo/js/**/*.js',
'vendor/bower_components/**/*.js',
'ng/**/*.js',
'test/**/*Spec.js'
],
config: {
paths: {
'systemjs': 'vendor/bower_components/system.js/dist/system.js',
'system-polyfills': 'vendor/bower_components/system.js/dist/system-polyfills.js'
}
}
},
// list of files / patterns to load in the browser
files: [
{pattern: 'vendor/kendo/js/**/*.js', included: false},
{pattern: 'vendor/bower_components/**/*.js', included: false},
{pattern: 'ng/**/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
});
};
module.exports = configure;
//# sourceMappingURL=karma.conf.js.map
Error
I fixed this by moving the bootstrap code out of the config code. Apparently when using the karma-systemjs plugin System.import is not available yet when this is called (although it is at normal runtime).
What I did: I moved the bootstrap code (i.e. Promise.all([....) into into a separate file called bootstrap.js (name is not important) and then in my index.html I added them in this order:
Also from this link (the karma system js plugin author says): https://github.com/rolaveric/karma-systemjs/issues/71
I see the problem. It's because you've got your bootstrapping code
(eg. System.import() calls) inside your SystemJS config file -
system.conf.js karma-systemjs expects just a simple System.config()
call that it can then intercept to find out where your transpiler and
polyfills are. It does this by evaluating your config file with a fake
System object which simply records whatever is passed to
System.config(). This fake object has no System.import() method, which
causes your error.
I'd recommend moving your bootstrapping code into a separate file (I
personally put it in a script tag with my HTML). Otherwise you'll run
into similar problems if you try to use systemjs-builder, and you
probably don't want angular.bootstrap() to be called at the start of
your unit tests.

Gruntjs: How to make copy task to copy only changed files on watch

So on grunt-contrib-watch plugin info page, there is an example on how to make jshint run only for changed file.
grunt.initConfig({
watch: {
scripts: {
files: ['lib/*.js'],
tasks: ['jshint'],
options: {
nospawn: true,
},
},
},
jshint: {
all: ['lib/*.js'],
},
});
grunt.event.on('watch', function(action, filepath) {
grunt.config(['jshint', 'all'], filepath);
});
I have not tested example it self. But took this and applied to my copy task, unsuccessfully.
grunt-contrib-copy task set up to copy images and templates for my angular project. And I would be happy to know if I can make this work for copy task and if I can, what am I doing wrong.
Thank you so much.
Here is my stripped out Gruntfile.js.
// Build configurations.
module.exports = function(grunt){
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Copies directories and files from one location to another.
copy: {
// DEVELOPMENT
devTmpl: {
files: [{
cwd : 'src/tpl/',
src : ['**/*'],
dest : 'app/tpl/',
flatten : false,
expand : true
}]
},
devImg: {
files: [{
cwd : 'src/img/',
src : ['**/*'],
dest : 'app/img/',
flatten : false,
expand : true
}]
}
},
// Watch files for changes and run tasks
watch: {
// Templates, copy
templates: {
files : 'src/tpl/**/*',
tasks : ['copy:devTmpl'],
options: {
nospawn: true,
}
},
// Images, copy
images: {
files : 'src/img/**/*',
tasks : ['copy:devImg'],
options: {
nospawn: true,
}
}
}
});
// Watch events
grunt.event.on('watch', function(action, filepath) {
// configure copy:devTmpl to only run on changed file
grunt.config(['copy','devTmpl'], filepath);
// configure copy:devImg to only run on changed file
grunt.config(['copy','devImg'], filepath);
});
// PLUGINS:
grunt.loadNpmTasks('grunt-contrib-copy');
// TASKS:
/* DEV: Compiles the app with non-optimized build settings, places the build artifacts in the dist directory, and watches for file changes.
run: grunt dev */
grunt.registerTask('dev', 'Running "DEVELOPMENT", watching files and compiling...', [
'default',
'watch'
]);
/* DEFAULT: Compiles the app with non-optimized build settings and places the build artifacts in the dist directory.
run: grunt */
grunt.registerTask('default', 'Running "DEFAULT", compiling everything.', [
'copy:devTmpl',
'copy:devImg'
]);
}
Use grunt-sync (https://npmjs.org/package/grunt-sync) instead of grunt-contrib-copy, and watch the directories you want to be synced.
Update - here's an example:
grunt.initConfig({
sync: {
copy_resources_to_www: {
files: [
{ cwd: 'src', src: 'img/**', dest: 'www' },
{ cwd: 'src', src: 'res/**', dest: 'www' }
]
}
}
});
cwd means current working directory. copy_resources_to_www is just a label.
You need to point grunt.config to the correct property in your config:
grunt.event.on('watch', function(action, filepath) {
var cfgkey = ['copy', 'devTmpl', 'files'];
grunt.config.set(cfgkey, grunt.config.get(cfgkey).map(function(file) {
file.src = filepath;
return file;
}));
});
I have written a detailed example configuration file for synchronizing changed files in my projects. It runs automatically in any related project, and it can be updated to suit your specific needs.
Grunfile.js
module.exports = function (grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
sync: {
main: {
files: [
{
cwd: ".",
src: ["src/**", "LICENSE", "README.md"],
dest: "dist/<%= pkg.name%>/",
},
],
verbose: true,
pretend: false,
failOnError: true,
ignoreInDest: "**/.git/**",
updateAndDelete: true,
compareUsing: "md5",
},
}
});
grunt.util.linefeed = "\n";
};