I'm trying to import only collapse component from Bootstrap JS components like this:
import "../../../node_modules/bootstrap/js/dist/collapse";
Everything is fine except jQuery, this file (collapse.js) is requiring jquery and it's get compiled to my main.js file, how to avoid that? I have included jQuery from CDN.
Here is my Gulp/Webpack config
let webpackConfig = {
module: {
rules: [
{
test: /.js$/,
use: [
{
loader: 'babel-loader'
}
]
}
]
}
};
// Combine JavaScript into one file
// In production, the file is minified
function javascript() {
return gulp.src(PATHS.entries)
.pipe(named())
.pipe($.sourcemaps.init())
.pipe(webpackStream(webpackConfig, webpack2))
.pipe($.if(PRODUCTION, $.uglify()
.on('error', e => { console.log(e); })
))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest(PATHS.dist + '/assets/js'));
}
UPDATE, SOLUTION:
let webpackConfig = {
externals: { jquery: 'jQuery' },
module: {
rules: [
{
test: /.js$/,
use: [
{
loader: 'babel-loader'
}
]
}
]
}
};
You can use the externals settings from Webpack to stop it from including some packages into your bundle.
Related
I'm trying to run the Feature file using cucumber in Cypress 10.2.0.
It is throwing me an issue of "WebPack Compilation Error"
Error: Webpack Compilation Error
./cypress/e2e/BankManagerLogin.feature 1:14
Module parse failed: Unexpected token (1:14)
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
any help would be appreciated
The cypress.config file needs adjusting to clear that error.
Try this, it's bolier-plate code from the badeball repository.
This assumes you have Typescript (let me know if you're only using Javascript).
import { defineConfig } from "cypress";
import * as webpack from "#cypress/webpack-preprocessor";
import { addCucumberPreprocessorPlugin } from "#badeball/cypress-cucumber-preprocessor";
async function setupNodeEvents(
on: Cypress.PluginEvents,
config: Cypress.PluginConfigOptions
): Promise<Cypress.PluginConfigOptions> {
await addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
webpack({
webpackOptions: {
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [
{
test: /\.ts$/,
exclude: [/node_modules/],
use: [
{
loader: "ts-loader",
},
],
},
{
test: /\.feature$/,
use: [
{
loader: "#badeball/cypress-cucumber-preprocessor/webpack",
options: config,
},
],
},
],
},
},
})
);
// Make sure to return the config object as it might have been modified by the plugin.
return config;
}
export default defineConfig({
e2e: {
specPattern: "**/*.feature",
supportFile: false,
setupNodeEvents,
},
});
I'm trying to add .MDX support in Nx for Storybook using #storybook/addon-docs package, but doesn't work.
I am keeping in mind the NPM package documentation (https://www.npmjs.com/package/#storybook/addon-docs#preset-options) as Nx documentation is sparse and Storybook documentation confusing.
The Nx version that I'm using is 12.6.5 for Angular and 6.3.7 for Storybook.
This is may main.js config file:
const rootMain = require('../../../.storybook/main');
module.exports = {
...rootMain,
core: { ...rootMain.core, builder: 'webpack5' },
stories: [...rootMain.stories, '../src/lib/**/*.stories.#(js|jsx|ts|tsx|mdx)'],
addons: [...rootMain.addons],
webpackFinal: async (config, { configType }) => {
// apply any global webpack configs that might have been specified in .storybook/main.js
if (rootMain.webpackFinal) {
config = await rootMain.webpackFinal(config, { configType });
}
// add your own webpack tweaks if needed
config.module.rules.push({
test: /\.(stories|story)\.mdx$/,
use: [
{
loader: 'babel-loader',
},
{ loader: '#mdx-js/loader' },
],
});
config.module.rules.push({
test: /\.(stories|story)\.[tj]sx?$/,
loader: require.resolve('#storybook/source-loader'),
exclude: [/node_modules/],
enforce: 'pre',
});
return config;
},
};
And also this is my preview.js config file:
import '#angular/localize/init';
import { DocsContainer, DocsPage } from '#storybook/addon-docs';
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
docs: {
container: DocsContainer,
page: DocsPage,
},
};
Anyone has a solution?
i have a working marko setup for my widget. Im using webpack 4 and babel 7. When i add babel-loader to .marko files, the webpack compiler throws because it couldn't recognize marko's syntax as valid javascript. However the loader should work after the marko transpilation.
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Volumes/Workspace/product-curator-widget/src/index.marko: A class name is required (1:6)
> 1 | class {
| ^
2 | onCreate () {
index.marko
class {
onCreate () {
this.state = {
items: [ {label: 'foo'}, {label: 'bar'} ]
}
const pr = new Promise((resolve) => resolve()) //trying to transpile this arrow function
}
}
<paper>
<chip for (item in state.items) label="${item.label}" value="${item.value}" />
</paper>
webpack.config.js
'use strict'
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports = () => ({
mode: 'development',
devtool: 'cheap-source-map',
entry: [
'core-js',
'./src/index.js'
],
resolve: {
extensions: ['.js', '.marko'],
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/, /\.test\.js$/],
use: ['babel-loader'],
},
{
test: /\.marko$/,
exclude: [/node_modules/, /\.test\.js$/],
use: ['#marko/webpack/loader', 'babel-loader'],
},
{
test: /\.scss$/,
exclude: [/node_modules/],
use: ['style-loader', 'css-loader', 'sass-loader'],
}
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: './src/index.html'
}),
new CleanWebpackPlugin()
],
})
babel.config.js
module.exports = function (api) {
api.cache(true)
return {
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-regenerator",
],
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "10"
}
}
]
]
}
}
Loaders in webpack are evaluated from right to left. In this case, you'll want #marko/webpack/loader to be the first loader to run (put it last in the array), so by the time babel-loader is called, the .marko file has been compiled to JS.
Side note: if you're using Marko components that have been published to npm, you don't want to ignore node_modules. Marko recommends publishing the source .marko files because the compiler produces different output for the server vs the browser. Additionally, the compilation output can be different depending on the version of Marko your app is using.
{
test: /\.marko$/,
use: ['babel-loader', '#marko/webpack/loader'],
},
I have a React app (ejected from create-react-app) and I'm trying to add PostCSS to the Webpack configuration.
Here's my (shortened) webpack.config.js:
...
const postCSSConfig = require('./postcss.config');
module.exports = {
...
module: {
loaders: [
...
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?importLoaders=1',
'postcss-loader'
]
},
...
]
},
postcss: function () {
return postCSSConfig;
},
...
Here's my postcss.config.js:
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
My file structure is:
project/
src/
assets/
components/
styles/
views/
index.js
package.json
postcss.config.js
webpack.config.js
When I try to make my CSS include some of the features in PreCSS (like nesting and variables, for example), it breaks the styling and doesn't work. But, the autoprefixer works. I've run npm install for PreCSS and tried rearranging things, but still no luck. Any advice would be appreciated.
Did you try to just include your post-css configuration directly into your webpack config ? I had success doing that, I can't really find any documentation regarding postcss.config and how properly write them.
module.exports = {
...
module: {
loaders: [
...
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?importLoaders=1',
'postcss-loader'
]
},
...
]
},
postcss: function () {
return [
require('precss'),
require('autoprefixer')
];
}
};
I'm using a Yeoman project template called "aspnetcore-spa", which is an ASP.net core 1 template working in conjunction with major SPA frameworks (Angular2 and React).
I created a project with Angular2.The biolerplate's code works fine and there is no problem. Once I add Sass loader to webpack.config.js and make a reference to the Sass file from any angular file.
In webpack.config.js :
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.scss$/,include:/ClientApp/, loaders: ["style", "css", "sass"] },
{ test: /\.html$/,include: /ClientApp/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
};
// Configuration for client-side bundle suitable for running in browsers
var clientBundleOutputDir = './wwwroot/dist';
var clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map',
externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});
module.exports = [clientBundleConfig, serverBundleConfig];
In my component :
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-wine',
template: require('./wine.component.html'),
styles: require('./wine.component.scss')
})
export class WineComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
I have already installed npm packages pertinent to sass loader :
npm install node-sass sass-loader --save-dev
I have checked the main-server.js file in wwwroot/dist folder which is the result of webpack bundling, I saw that the .scss file is loaded and they styles are processed correctly. Once I run the app though, shows this exception which is coming from the server side rendering side:
An unhandled exception occurred while processing the request.
Exception: Call to Node module failed with error: ReferenceError: window is not defined at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:573:31 at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:568:48 at module.exports (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:590:69) at Object. (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:526:38) at webpack_require (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30) at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:501:22 at Object.module.exports (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:506:3) at webpack_require (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30) at Object. (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:129:25) at webpack_require (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30)
It's obviously because of the webpack's server-side rendering, as it's running the code on Node.js side (through ASP.net Core's Javascript Services) and there is a code that is coupled with the DOM window object which is not valid on node.
Any clues?
I managed to fix the problem, here's the web.config.js bit:
(Notice the loaders for .scss files)
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.scss$/,include:/ClientApp/, loaders: ["to-string", "css", "sass"] },
{ test: /\.html$/,include: /ClientApp/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
And in the Angular component I changed the styles to this :
(Passed an array of required css files rather than a single css file)
#Component({
selector: 'app-wine',
template: require('./wine.component.html'),
styles: [require('./wine.component.scss')]
})