module is not defined at node_modules/core-js/internals/global.js - javascript

I'm building a library in TypeScript, and I'm trying to test it. As It involves browser API I'm testing it using #web/test-runner and chai.
I'm using TypeScript, and some libraries are commonjs modules, so I'm using Rollup to bundle all of that into something the browser can use.
My rollup config is as follow:
import typescript from '#rollup/plugin-typescript';
import commonjs from '#rollup/plugin-commonjs';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import json from '#rollup/plugin-json';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { babel } from '#rollup/plugin-babel';
import nodePolyfills from 'rollup-plugin-node-polyfills';
const pkg = require('./package.json');
const libraryName = 'AGreatLibrary';
export default {
input: 'src/index.ts',
output: [
{ file: pkg.main, name: libraryName, format: 'umd', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
],
plugins: [
json(),
nodePolyfills(),
typescript(),
commonjs(),
nodeResolve({ browser: true, preferBuiltins: false }),
sourceMaps(),
babel({ babelHelpers: 'bundled', exclude: [/\bcore-js\b/, /\bwebpack\/buildin\b/] }),
],
};
My babel config
{
"presets":
[
[
"#babel/env",
{
"targets":
{
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3"
}
]
],
"minified": true
}
My test file
import { Client } from "../lib/index.es.js";
import { expect } from '#esm-bundle/chai';
it('Should create a Client', () => {
let client = new Client("123", true);
expect(client.accessToken).to.equal("123");
});
it('Should auth', async () => {
let client = new Client("123", true);
let resp = await client.tryAuth();
expect(resp.ok).to.be.true;
});
But when I run my test (web-test-runner "test/**/*.test.ts" --node-resolve)
I get the following error
🚧 Browser logs:
ReferenceError: module is not defined
at node_modules/core-js/internals/global.js:6:0
I have no idea what to do.

I fix it!
plugins: [
commonjs(),
json(),
nodePolyfills(),
typescript(),
nodeResolve({ browser: true, preferBuiltins: false }),
sourceMaps(),
babel({ babelHelpers: 'bundled', exclude: [/\bcore-js\b/, /\bwebpack\/buildin\b/] }),
],
commonjs should be on top of the array.

Related

Library built with Webpack 5 not tree shakeable

I have a React component library that is built by webpack 5.75.0. The library exports 2 components:
// src/index.ts
export { default as ComponentA } from "components/ComponentA";
export { default as ComponentB } from "components/ComponentB";
A simple CRA app uses this library and imports only ComponentA. But when analyzing the bundle I see that ComponentB's dependencies are in it and have not been tree-shaken.
The parent app is just a CRA app with no config overrides. Tree shaking works there for other modules (MUI, lodash-es, etc), so the problem is with the my library.
I seem to have followed all requirements: in my package.json I do have
"sideEffects": false,
"main": "lib/index.js",
"module": "lib/index.js",
Here's my babel config:
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current", modules: false } }],
"#babel/preset-typescript",
[
"#babel/preset-react",
{
runtime: "automatic",
},
],
],
plugins: [
"#babel/plugin-syntax-jsx",
[
"#babel/plugin-transform-runtime",
{
regenerator: true,
useESModules: true,
},
],
],
};
And here's my webpack config:
const config = {
mode: "production",
devtool: false,
entry: "./src/index.ts",
output: {
path: path.resolve(__dirname, "lib"),
filename: "index.js",
module: true,
library: {
type: "module",
},
},
plugins: [
//...
],
module: {
rules: [
//...
],
},
resolve: {
//...
},
externals: [
"react",
"react-dom",
],
experiments: {
outputModule: true,
},
optimization: {
minimize: false,
},
};
But still, the ComponentB's dependencies are showing up in the bundle of the CRA app that uses this library.
Am I missing something? Is there some official example of how to configure tree-shaking library with webpack 5?
Thanks.
P.S. My question relates to this question, but since 2021 it's become possible to build ES modules with Webpack 5.

How to extract all used polyfill from multiple libs by rollup?

I use rollup to create multiple libs, rollup config file as below:
import terser from '#rollup/plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import { babel } from '#rollup/plugin-babel';
import eslint from '#rollup/plugin-eslint';
const distDir = "dist/libs"
const api = {
input: "src/libs/api/index.js",
external: ["axios"],
output: [
{
file: `${distDir}/api.umd.js`,
format: "umd",
name: 'Api',
globals: {axios: 'axios'}
},
{
file: `${distDir}/api.es.js`,
format: "es"
}
],
plugins: [
terser(),
babel({babelHelpers: 'runtime', exclude: 'node_modules/**'}),
nodeResolve({
browser:true,
}),
commonjs(),
eslint({
throwOnError: true,
throwOnWarning: true,
include: ['src/**'],
exclude: ['node_modules/**']
})
]
}
const test = {
...
}
export default ()=>{
return [
api, // it contains some polyfill
test // it also contains some polyfill
]
};
My .babelrc is:
{
"presets": [
["#babel/preset-env", {
"corejs": {"version": "3", "proposals": false},
"useBuiltIns": "usage"
}
]
],
"plugins": [
[
"#babel/plugin-transform-runtime"
]
]
}
Now, api and test contain some polyfill. Is there a way to extract the used polyfills of all modules to form a single umd file but not Full Function polyfill.Thank you.

How to configure Storybook to run from a directory other than the project root

I'm trying to configure Storybook to run from a directory that is not the root of the project and I'm having a little trouble. I've setup a mono-rep using https://github.com/jibin2706/cra-monorepo-demo as base.
My project directory looks like this:
- project
-- packages
---- app
---- components
---- utils
---- stories
------ .storybook
-------- main.js
------ ComponentA
-------- ComponentA.stories.mdx
Because I'm using a monorep with aliases (e.g. a component can import from #project/utils) I've configured webpack in .storybook/main.js to read like:
const path = require('path');
module.exports = {
stories: ['../**/*.stories.mdx', '../../**/*.stories.#(js|jsx|ts|tsx)'],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/preset-create-react-app',
],
webpackFinal: async (config, { configType }) => {
const result = {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
'#project/components': path.resolve(
process.cwd(),
'packages/components'
),
},
},
};
},
};
Then within my ComponentA.stories.mdx I have an import like import { ComponentA } from '#project/components';
When I run this however, I'm always hitting an error when it encounters JSX within a .js file:
ERROR in ./packages/components/MyComponent1/MyComponent1.js 106:11
Module parse failed: Unexpected token (106:11)
File was processed with these loaders:
./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
|
return <React.Fragment>{children}</React.Fragment>;
I can't seem to work out why this error is throwing. I've tried running with yarn storybook --debug-webpack which seems to include a loader for both jsx and js files. I'm not 100% sure if this is correct, but it looks roughly right from other docs I've read.
module: {
rules: [
{
test: /\.(mjs|tsx?|jsx?)$/,
use: [
{
loader: '/home/ian/src/cra-monorepo-demo/node_modules/babel-loader/lib/index.js',
options: {
sourceType: 'unambiguous',
presets: [
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/preset-env/lib/index.js',
{ shippedProposals: true, loose: true }
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/preset-typescript/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/preset-react/lib/index.js'
],
plugins: [
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-shorthand-properties/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-block-scoping/lib/index.js',
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-decorators/lib/index.js',
{ legacy: true }
],
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-class-properties/lib/index.js',
{ loose: true }
],
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-private-methods/lib/index.js',
{ loose: true }
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-export-default-from/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-syntax-dynamic-import/lib/index.js',
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-object-rest-spread/lib/index.js',
{ loose: true, useBuiltIns: true }
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-classes/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-arrow-functions/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-parameters/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-destructuring/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-spread/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-for-of/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#storybook/core-common/node_modules/babel-plugin-macros/dist/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-optional-chaining/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-nullish-coalescing-operator/lib/index.js',
[
'/home/ian/src/cra-monorepo-demo/node_modules/babel-plugin-polyfill-corejs3/lib/index.js',
{
method: 'usage-global',
absoluteImports: '/home/ian/src/cra-monorepo-demo/node_modules/core-js/index.js',
version: '3.16.1'
}
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-template-literals/lib/index.js'
]
}
}
],
include: [ '/home/ian/src/cra-monorepo-demo' ],
exclude: [ /node_modules/, /dist/ ]
},
{
test: /\.js$/,
use: [
{
loader: '/home/ian/src/cra-monorepo-demo/node_modules/babel-loader/lib/index.js',
options: {
sourceType: 'unambiguous',
presets: [
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/preset-env/lib/index.js',
{
shippedProposals: true,
modules: false,
loose: true,
targets: 'defaults'
}
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/preset-react/lib/index.js'
],
plugins: [
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-shorthand-properties/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-block-scoping/lib/index.js',
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-decorators/lib/index.js',
{ legacy: true }
],
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-class-properties/lib/index.js',
{ loose: true }
],
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-private-methods/lib/index.js',
{ loose: true }
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-export-default-from/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-syntax-dynamic-import/lib/index.js',
[
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-object-rest-spread/lib/index.js',
{ loose: true, useBuiltIns: true }
],
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-classes/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-arrow-functions/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-parameters/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-destructuring/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-spread/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-transform-for-of/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#storybook/core-common/node_modules/babel-plugin-macros/dist/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-optional-chaining/lib/index.js',
'/home/ian/src/cra-monorepo-demo/node_modules/#babel/plugin-proposal-nullish-coalescing-operator/lib/index.js',
[
'/home/ian/src/cra-monorepo-demo/node_modules/babel-plugin-polyfill-corejs3/lib/index.js',
{
method: 'usage-global',
absoluteImports: '/home/ian/src/cra-monorepo-demo/node_modules/core-js/index.js',
version: '3.16.1'
}
]
]
}
}
],
include: [Function: include]
},
...
Can anyone see what I might be missing here, or what additional config is required?
The issue is probably with the Storybook project root. The default babel-loader defines an include that is equal to the project root. And the "project root" is usually the closest .git folder.
A workaround is to set the correct project root:
const path = require("path");
module.exports = {
// ...
webpackFinal: async (config, { configType }) => {
const babelLoaderRule = config.module.rules.find(
(rule) => rule.test.toString() === /\.(mjs|tsx?|jsx?)$/.toString()
);
// set correct project root
babelLoaderRule.include = [path.resolve(__dirname, "../..")];
return config;
}
};
What "correct" path is, depends on your setup.
Check my post for a longer write-up.
As far as I can tell your .storybook/main.js looks fine.
The built-in loader should also work as expected.
Concerning the error you're seeing: have you tried changing the file-type (aka renaming the file ending) from .js to .jsx?
Because the loader can discern between .js and .jsx files, however the interpreter cannot comprehend jsx-notation if it's not explicitely told to do so (as is the case with your .js files).

Jest won't transform node_module dependencies

Our code references the #myScope/vue-notify library which is set as a external/global in our rollup config. That code is an ES6 module and needs to be transpiled for jest to be able to work with it but by default Jest doesn't transpile node_modules folder. I have tried adding a negative lookahead to the transformIgnorePatterns but no matter what combination I try I just keep getting this error:
My Jest transform settings are as follows:
transform: {
'.+\\.(css|css!|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.(js|jsx)?$': 'babel-jest',
},
transformIgnorePatterns: [
'/node_modules/(?!#myScope/vue-notify)',
'/dist/',
'/docs/',
],
My rollup.config.js is as follows:
import packageJson from './package.json';
import json from '#rollup/plugin-json';
import babel from '#rollup/plugin-babel';
import { addMinExtension } from './utils/utils';
import { terser } from 'rollup-plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
const globals = {
DevExpress: 'DevExpress',
jquery: '$',
'#myScope/vue-notify': 'vueNotify',
'file-saver': 'saveAs',
exceljs: 'ExcelJS',
};
const externals = ['jquery', '#myScope/vue-notify', 'file-saver', 'exceljs'];
export default [
{
// Dev UMD Config:
input: packageJson.input,
output: [
{
name: packageJson.moduleName,
file: packageJson.browser,
format: 'umd',
globals: globals,
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
babel({ babelHelpers: 'runtime' }),
],
},
{
// Dev Module Config:
input: packageJson.input,
output: [
{
file: packageJson.module,
format: 'es',
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
],
},
{
// Prod UMD Config:
input: packageJson.input,
output: [
{
name: packageJson.moduleName,
file: addMinExtension(packageJson.browser),
format: 'umd',
sourcemap: true,
globals: globals,
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
babel({ babelHelpers: 'runtime' }),
terser(),
],
},
{
// Prod Module Config:
input: packageJson.input,
output: [
{
file: addMinExtension(packageJson.module),
format: 'es',
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
terser(),
],
},
];
Any help getting this working would be much appriciated!

Webpack2 + Typescript2 fails to dynamic import json

I have a problem at import json dynamically using webpack.
(https://webpack.js.org/api/module-methods/#import-)
It keep shows this error - TS2307: Cannot find module
package versions are..
webpack version: 2.7.0
typescript version: 2.4.2
awesome-typescript-loader: 3.2.1
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "esnext",
"moduleResolution": "node",
"target": "es6",
"jsx": "react",
"allowJs": true,
"allowSyntheticDefaultImports": true
},
"awesomeTypescriptLoaderOptions": {
"useBabel": true,
"useCache": true
},
"exclude": ["node_modules"],
"include": [
"./components/**/*",
"./core/*",
"./pages/*",
"./utils/*",
"./urls/*",
"./translations/**/*",
"./main.tsx"
]
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const AssetsPlugin = require('assets-webpack-plugin');
const pkg = require('./package.json');
const isDebug = global.DEBUG === false ? false : !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose') || process.argv.includes('-v');
const useHMR = !!global.HMR; // Hot Module Replacement (HMR)
const babelConfig = Object.assign({}, pkg.babel, {
babelrc: false,
cacheDirectory: useHMR,
});
// Webpack configuration (main.js => public/dist/main.{hash}.js)
// http://webpack.github.io/docs/configuration.html
const config = {
// The base directory for resolving the entry option
context: __dirname,
// The entry point for the bundle
entry: [
// require('babel-polyfill'),
'./main.tsx'
],
// Options affecting the output of the compilation
output: {
path: path.resolve(__dirname, './public/dist'),
publicPath: '/dist/',
filename: isDebug ? '[name].js?[hash]' : '[name].[hash].js',
chunkFilename: isDebug ? '[id].js?[chunkhash]' : '[id].[chunkhash].js',
sourcePrefix: ' ',
},
// Developer tool to enhance debugging, source maps
// http://webpack.github.io/docs/configuration.html#devtool
devtool: isDebug ? 'inline-source-map' : false,
// What information should be printed to the console
stats: {
colors: true,
reasons: isDebug,
hash: isVerbose,
version: isVerbose,
timings: true,
chunks: isVerbose,
chunkModules: isVerbose,
cached: isVerbose,
cachedAssets: isVerbose,
},
// The list of plugins for Webpack compiler
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
__DEV__: isDebug,
}),
// Emit a JSON file with assets paths
// https://github.com/sporto/assets-webpack-plugin#options
new AssetsPlugin({
path: path.resolve(__dirname, './public/dist'),
filename: 'assets.json',
prettyPrint: true,
}),
],
// Options affecting the normal modules
module: {
rules: [
{
test: /\.tsx?$/,
include: [
path.resolve(__dirname, './components'),
path.resolve(__dirname, './core'),
path.resolve(__dirname, './pages'),
path.resolve(__dirname, './apis'),
path.resolve(__dirname, './urls'),
path.resolve(__dirname, './translations'),
path.resolve(__dirname, './main')
],
loader: 'awesome-typescript-loader'
},
{
test: /\.css/,
use: [{loader: 'style-loader'}, {loader: 'css-loader', options:
{
sourceMap: isDebug,
// CSS Modules https://github.com/css-modules/css-modules
modules: true,
localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
// CSS Nano http://cssnano.co/options/
minimize: !isDebug,
}},
// {loader: 'postcss-loader'}
],
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000',
},
{
test: /\.(eot|ttf|wav|mp3)$/,
loader: 'file-loader',
},
],
},
externals: {
react: 'React'
},
resolve: {
extensions: ['.js', '.ts', '.tsx']
}
};
// Optimize the bundle in release (production) mode
if (!isDebug) {
config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: isVerbose }, sourceMap: isDebug }));
config.plugins.push(new webpack.optimize.AggressiveMergingPlugin());
}
// Hot Module Replacement (HMR) + React Hot Reload
if (isDebug && useHMR) {
babelConfig.plugins.unshift('react-hot-loader/babel');
config.entry.unshift('react-hot-loader/patch', 'webpack-hot-middleware/client');
config.plugins.push(new webpack.HotModuleReplacementPlugin());
config.plugins.push(new webpack.NoEmitOnErrorsPlugin());
}
module.exports = config;
custom.d.ts
declare module "*.json" {
const value: any;
export default value;
}
my error code
// TS2307: Cannot find module './test.json'.
import('./test.json').then(_ => {
console.log(_
})
// but these codes work
import './test.json'
import('./test.js').then(_ => { console.log(_)})
I have searched issues as much as possible I can. but no one seems to encountered this issue.
Here's related links what I found.
https://github.com/Microsoft/TypeScript/issues/16820
https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/
If anyone have a clue, please let me know.
Are you sure your custom.d.ts is in a folder included in the compilation? I believe only typings in packages under node_modules/#types are included if they are not in the "files" or "include" properties in tsconfig.json.

Categories

Resources