How to separate source file from all vendors in webpack? - javascript

I want to have two files app.bundle.js and vendors.js where app.bundle.js contains only the code I wrote. Is it possible?
Here is my webpack.config.js file now
const dependencies = _.keys(packageConfig["dependencies"])
export default {
entry: {
vendors: dependencies,
app: [
'webpack-hot-middleware/client',
'./src/js/entry.js'
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
publicPath: '/'
},
...
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
...
But it does not work. I always had an error when compiling because some modules are not found. I've tried to list all dependencies manually, but in such case I have third party code in my app.bundle.js. So is it even possible?
UPDATE
I've take a look into the compiled app.bundle.js and saw code from hot replacement module and webpack itself. So the real question is - is this a default code that have to be placed inside each webpack module?
UPDATE
My first line in the entry file is import 'babel-core/polyfill' so I want module babel-core to be in vendors.js. And have this error
ERROR in ./~/babel-core/~/regenerator/lib/visit.js
Module not found: Error: Cannot resolve module 'fs' in /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/regenerator/lib
# ./~/babel-core/~/regenerator/lib/visit.js 12:9-22
ERROR in ./~/babel-core/~/regexpu/data/iu-mappings.json
Module parse failed: /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/regexpu/data/iu-mappings.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "75": 8490,
| "83": 383,
| "107": 8490,
# ./~/babel-core/~/regexpu/rewrite-pattern.js 4:17-51
ERROR in ./~/babel-core/~/globals/globals.json
Module parse failed: /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/globals/globals.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "builtin": {
| "Array": false,
| "ArrayBuffer": false,
# ./~/babel-core/~/globals/index.js 1:17-42
ERROR in ./~/babel-core/~/regenerator/~/recast/main.js
Module not found: Error: Cannot resolve module 'fs' in /Users/vitalii/Documents/coding/timerrrs/node_modules/babel-core/node_modules/regenerator/node_modules/recast
# ./~/babel-core/~/regenerator/~/recast/main.js 18:4-17

Related

Vite resolve static asset path

In vite.config.js i have set up:
resolve: {
alias: [
{ find: '~ext', replacement: path.resolve(__dirname, './src/assets/ext') },
Now I try to resolve a path (not a file!) in main.js:
import myDir from '~ext/SomeDir/'
console.log(myDir);
Could not load C:\prj\MyProject\src\assets\ext/SomeDir(imported by src/assets/js/main.js):
EISDIR: illegal operation on a directory, read
Resolving a file ~ext_/SomeDir/somefile.txt_ works fine.
Is there a way to get the path resolved in Vite?
(without having a dummy file and stripping the filename)?
import myDir from '~ext/SomeDir/?url' gives me /#fs/assets/ext/SomeDir/, so I have to remove the #fs there too I guess

Next.js and Jest: SyntaxError: Cannot use import statement outside a module

I am working on a Next.js project using TypeScript and for testing I use Jest and React Testing Lib. However, I encounter a SyntaxError: Cannot use import statement outside a module for components where I import rehype-raw.
As far as I understand this, Jest does not support ES6 so node_modules may need to be transformed. This can be configured using transformIgnorePatterns. For example if rehype-raw is causing this error using "transformIgnorePatterns": ["node_modules/(?!rehype-raw)/"] should allow transformation of the rehype-raw but no other module. And thus solve this error.
However, this does not work for me. But idk why and how I can solve this. No suggested solution I have found could solve this problem. I have attached my error output, jest.config.js and babel.rc file below.
Error output
FAIL test/pages/companies/[id].test.tsx
● Test suite failed to run
Jest encountered an unexpected token
[...]
Details:
/path/frontend-job/node_modules/rehype-raw/index.js:7
import {raw} from 'hast-util-raw'
^^^^^^
SyntaxError: Cannot use import statement outside a module
3 | import Image from 'next/image';
4 | import { Remark } from 'react-remark';
> 5 | import rehypeRaw from 'rehype-raw';
| ^
6 | import rehypeSanitize from 'rehype-sanitize';
7 | import { logError } from '#utils/logger';
8 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (components/markdown/JobMarkdown.tsx:5:1)
jest.config.js
const { resolve } = require('path');
module.exports = {
roots: ['<rootDir>'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
setupFiles: ['<rootDir>/test/setup.js'],
testPathIgnorePatterns: ['<rootDir>[/\\\\](node_modules|.next)[/\\\\]'],
transform: {
'^.+\\.(ts|tsx)$': 'babel-jest',
},
transformIgnorePatterns: [
'node_modules/(?!rehype-raw)/',
],
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
moduleNameMapper: {
// Force mocks: https://github.com/facebook/jest/issues/4262
'#api/axios': '<rootDir>/test/__mocks__/axios.js',
// Normal module aliases
'\\.(css|less|sass|scss)$': 'identity-obj-proxy',
'\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__mocks__/fileMock.js',
'^#test/(.*)$': resolve(__dirname, './test/$1'),
'^#test/faker/(.*)$': resolve(__dirname, './test/faker/$1'),
'^#components/(.*)$': resolve(__dirname, './components/$1'),
'^#pages/(.*)$': resolve(__dirname, './pages/$1'),
'^#utils/(.*)$': resolve(__dirname, './utils/$1'),
'^#api/(.*)$': resolve(__dirname, './api/$1'),
'^#store/(.*)$': resolve(__dirname, './store/$1'),
},
testEnvironment: 'jsdom',
};
babel.rc
{
"presets": ["next/babel"]
}
Did you already use type:"module" in package.json?
Next has already out-of-the-box support for Jest, I'd suggest you follow the steps provided in the docs.

How to use svelte in an exising project?

I'm new to svelte and I'm trying to use it in my existing project following this tutorial. So in svelte's main.js I outputs css and js like this:
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: '/path/to/myapp/static/js/svelte-bundle.js'
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({
output: '/path/to/myapp/static/css/svelte-bundle.css'
}),
However after npm run dev I get this error:
svelte-app#1.0.0 dev
rollup -c -w
rollup v2.56.3
bundles src/main.js → ../static/js/svelte-bundle.js...
[!] (plugin css) Error: The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "/path/to/myapp/static/css/svelte-bundle.css".
Error: The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "/path/to/myapp/static/css/svelte-bundle.css".
at error (/path/to/myapp/svelte-components/node_modules/rollup/dist/shared/rollup.js:151:30)
at FileEmitter.emitFile (/path/to/myapp/svelte-components/node_modules/rollup/dist/shared/rollup.js:13119:24)
at Object.generateBundle (/path/to/myapp/svelte-components/node_modules/rollup-plugin-css-only/dist/index.cjs.js:84:12)
at /path/to/myapp/svelte-components/node_modules/rollup/dist/shared/rollup.js:20218:25
I have also added the scripts to myapp's html:
<link href="/static/css/svelte-bundle.css" />
<script defer src="/static/js/svelte-bundle.js"></script>
Also in browser I get:
http://127.0.0.1:8080/static/svelte-bundle.js net::ERR_ABORTED 404 (Not Found)
Apprecite your help to fix this.

How to include oasis.js from Bower in a webpack build?

I'm using webpack to build my project and I'm having trouble getting it to include oasis.js, specifically https://raw.githubusercontent.com/tildeio/oasis.js/4c657d15a89c532382d2d174783f5c3660111765/dist/oasis.js as pulled in by Bower since there isn't an npm module available for it.
My webpack configuration looks like:
'use strict';
const BowerWebpackPlugin = require('bower-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: 'www',
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.html$/, loader: 'html-loader' },
{ test: /\.svg$/, loader: 'file-loader' }
]
},
plugins: [
new BowerWebpackPlugin({ excludes: [/oasis\.amd\.js$/] }),
new HtmlWebpackPlugin()
]
};
and my ./app/index.js which pulls in Oasis looks like:
'use strict';
var oasis = require('oasis.js');
When I run webpack -d, I get error a series of error messages like:
ERROR in ./bower_components/oasis.js/dist/oasis.js
Module not found: Error: Cannot resolve module 'oasis/xhr' in /Users/jeffreycharles/projects/dev-container/bower_components/oasis.js/dist
# ./bower_components/oasis.js/dist/oasis.js 2983:0-3092:4 3680:0-3780:4
ERROR in ./bower_components/oasis.js/dist/oasis.js
Module not found: Error: Cannot resolve module 'oasis/connect' in /Users/jeffreycharles/projects/dev-container/bower_components/oasis.js/dist
# ./bower_components/oasis.js/dist/oasis.js 2983:0-3092:4 3093:0-3189:4
ERROR in ./bower_components/oasis.js/dist/oasis.js
Module not found: Error: Cannot resolve module 'oasis/logger' in /Users/jeffreycharles/projects/dev-container/bower_components/oasis.js/dist
# ./bower_components/oasis.js/dist/oasis.js 2983:0-3092:4 3093:0-3189:4 3217:0-3404:4 3453:0-3679:4 3680:0-3780:4
ERROR in ./bower_components/oasis.js/dist/oasis.js
Module not found: Error: Cannot resolve module 'oasis/version' in /Users/jeffreycharles/projects/dev-container/bower_components/oasis.js/dist
# ./bower_components/oasis.js/dist/oasis.js 2983:0-3092:4
which I find odd since I can see define("oasis/xhr", on line 4961 in the oasis file and the other modules that webpack is saying it can't resolve are all in that same file I linked to.
I've also tried setting noParse and using the script-loader to load Oasis but then it complains about RSVP not being defined. This isn't an issue when I load Oasis using a script tag in my HTML (in fact it all works properly when I do that).
How do I get Webpack to build and include Oasis.js in my project?

Problems generating bundle with RequireJS

I have a Typescript project:
myproject
|
+-src (folder)
| |
| +-main.ts
| +-stringHandler.ts
| +-disposable.ts
+-out (folder)
| |
| +-...
+-Gruntfile.js
In my Grunt configuration I have a 2-step task which compiles all .ts files in myproject/src/ and generates corresponding .js files into myproject/out/. So after the first step of the task is complete, I have the following:
myproject
|
+-out (folder)
|
+-main.js
+-stringHandler.js
+-disposable.js
Bundling
The second step of the task is generating bundle file myproject.js. I am using RequireJS for this purpose.
I have installed grunt-contrib-requirejs. The Gruntfile.js file handling the bundling task is as follows (showing only relevant parts in the file):
module.exports = function(grunt) {
var config = {
pkg: grunt.file.readJSON('package.json'),
requirejs: {
compile: {
options: {
baseUrl: "out",
bundles: {
'myproject': ['main', 'stringHandler', 'disposable']
},
out: 'out/myproject.js'
}
}
}
};
grunt.initConfig(config);
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['compile', 'requirejs']);
};
When Grunt reaches requirejs, after successfully compiling the project, I get the following error:
Running "requirejs:compile" (requirejs) task { [Error: Error: Missing
either a "name", "include" or "modules" option
at Function.build.createConfig (C:\Users\myuser\Documents\myproject\node_modules\grunt-contrib-requirejs\node_modules\requirejs\bin\r.js:29567:19)
] originalError: [Error: Missing either a "name", "include" or
"modules" option] }
I can understand there are missing parameters, but when I use name I get other errors. I guess there must be something wrong at a more generic level. What is the correct configuration format? Thanks
This assumes main.ts is your application's entry point and that it contains a require.config section with your application dependencies (libraries and shims).
First, move the require.config section out of main.ts and into its own file, config.ts. Leave the application bootstrap code in main.ts.
Then determine where you want this optimized application code deployed. Let's assume it is to a directory named build, which is parallel to your src and out folders.
Update you Gruntfile to reflect this configuration:
requirejs: {
compile: {
options: {
baseUrl: "out",
mainConfigFile: "out/config.js",
modules: [
{ name: "main" }
],
dir: "build",
optimize: "none" // skip compression while debugging
}
}
}
You can read more about each of these config options at http://requirejs.org/ but here's the basic rundown:
baseUrl: Where the source JS code lives.
mainConfigFile: Points to the config object mentioned above. It tells the plugin where the dependencies live. This obviates the need to specify and manually update the list of dependencies in two places.
modules: Is an array of application bootstraps. In this case a list of one, main.js.
dir: Where the optimized application will be generated. Note that your dependencies will also be copied here.
optimize: I left this off so you can easily debug the resulting app under ./build. Remove it when you're happy and the plugin will optimize (compress and munge) your build files.

Categories