GithubHelp home page GithubHelp logo

salesforce / lwc-webpack-plugin Goto Github PK

View Code? Open in Web Editor NEW
2.0 13.0 5.0 472 KB

Plugin to use LWC within Webpack

Home Page: https://lwc.dev

License: BSD 3-Clause "New" or "Revised" License

TypeScript 50.81% JavaScript 49.19%

lwc-webpack-plugin's Introduction

lwc-webpack-plugin

This plugin allows you to use LWC within any web framework project that uses Webpack.

Install

npm install --save-dev lwc-webpack-plugin lwc @lwc/module-resolver

Note that you must install your own dependencies for lwc and @lwc/module-resolver.

Usage

const LwcWebpackPlugin = require('lwc-webpack-plugin')

module.exports = {
    plugins: [new LwcWebpackPlugin()]
}

The above example assumes that you have configured LWC modules via lwc.config.json in your project root, or as lwc key in your package.json. You can read more about module configuration in this blog, or in this RFC.

Pass the module configuration as parameter to the plugin, if you prefer to not use any of the above mentioned LWC module configuration options.

const LwcWebpackPlugin = require('lwc-webpack-plugin')

module.exports = {
    plugins: [
        new LwcWebpackPlugin({
            modules: [
                { npm: 'lwc-recipes-oss-ui-components' },
                { npm: 'lightning-base-components' }
            ]
        })
    ]
}

The plugin takes the following additional configuration options:

  • outputConfig

These options are 1:1 mappings of the LWC Compiler options, which are documented here.

stylesheetConfig has been deprecated as of lwc v3.1.3 and results in a NOOP.

Read more about Lightning Web Components here.

Live App

If you want to see Lightning Web Components in action - check out https://recipes.lwc.dev.

TypeScript

If you want to use TypeScript in your LWC components, you can install the necessary Babel dependencies:

npm install --save-dev \
    babel-loader@^8 \
    @babel/preset-typescript@^7 \
    @babel/plugin-syntax-decorators@^7

Then add this to your webpack.config.js:

module.exports = {
  plugins: [
    new LwcWebpackPlugin(),
    // Add this _after_ LwcWebpackPlugin:
    {
      apply(compiler) {
        compiler.options.module.rules.push({
          test: /\.ts$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-typescript'],
              plugins: [['@babel/plugin-syntax-decorators', { legacy: true }]],
            }
          }
        })
      }
    }
  ]
}

You may customize the babel-loader settings to suit your needs.

Tests

To run the tests in this repo, do:

yarn test

To update snapshot files:

UPDATE_SNAPSHOTS=1 yarn test

To run code coverage tests:

yarn test:coverage

lwc-webpack-plugin's People

Contributors

nolanlawson avatar dependabot[bot] avatar ekashida avatar lukethacoder avatar wjhsf avatar muenzpraeger avatar rui-rayqiu avatar

Stargazers

 avatar Bryden Wayne avatar

Watchers

Caridy Patiño avatar Abdulsattar Mohammed avatar  avatar Jose David Rodriguez Velasco avatar James Cloos avatar Ravi Jayaramappa avatar Demian Brecht avatar  avatar James Tu avatar  avatar  avatar  avatar  avatar

lwc-webpack-plugin's Issues

CSS Loading Problems

I am attempting to integrate LWC with Storybook at the moment, but I keep running into issues using LWC-specific styles. Initially, I had errors concerning css-loader trying to compile in the code from the associated LWC .css file. However, excluding the LWC path for css-loader did the trick. See here for more context: https://salesforce.stackexchange.com/a/360151

However, when I run storybook and the customized webpack, I get a similar runtime error:

TypeError: (0 , lwc__WEBPACK_IMPORTED_MODULE_0__.registerStylesheet) is not a function
	 at ./force-app/main/default/lwc/linkCard/linkCard.css

When I run the same configuration with just .HTML and .JS files in the LWC, everything works just fine. Looking into the linkCard.css file more, this is what the file gets rendered as:

linkCard.css

import { registerStylesheet } from 'lwc';
function stylesheet(token, useActualHostSelector, useNativeDirPseudoclass) {
  var shadowSelector = token ? ("[" + token + "]") : "";
  var hostSelector = token ? ("[" + token + "-host]") : "";
  var suffixToken = token ? ("-" + token) : "";
  return ".linkCard" + shadowSelector + " {display: flex;flex-direction: column;background-color: #fefefe;border-radius: 10px;box-shadow: 1px 1px 5px 5px rgb(0, 0, 0, .1);}.linkCard__link" + shadowSelector + ",.linkCard__link:link" + shadowSelector + ",.linkCard__link:visited" + shadowSelector + " {font-family: Georgia, 'Times New Roman', Times, serif;color: navy;font-size: 2.5rem;}.linkCard__description" + shadowSelector + " {font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;color: #222222;font-size: 1.2rem;}";
  /*LWC compiler v2.43.0*/
}
registerStylesheet(stylesheet);
export default [stylesheet];

Maybe this is some configuration I am missing, or something I am doing wrong, but it seems like the @lwc/compiler is causing this and I am wondering how I can get this CSS compiled and integrated into the component as its normal <style> tag before it is requested during runtime. I am opening this issue since I don't believe there is a way to do this currently with this plugin.

Remove Babel dependency and TypeScript transforms

Right now we do some TypeScript transforms with Babel:

if (resourcePath.endsWith('.ts')) {
const { code } = babel.transform(source, {
filename: resourcePath,
plugins: [
require.resolve('@babel/plugin-syntax-class-properties'),
[
require.resolve('@babel/plugin-syntax-decorators'),
{
decoratorsBeforeExport: true
}
],
require.resolve('@babel/plugin-proposal-optional-chaining'),
require.resolve(
'@babel/plugin-proposal-nullish-coalescing-operator'
)
],
presets: [
[
require.resolve('@babel/preset-typescript'),
{
allowDeclareFields: true
}
]
]
})
codeTransformed = code
}

...which adds to our dependencies:

"@babel/plugin-proposal-nullish-coalescing-operator": "~7.14.2",
"@babel/plugin-proposal-optional-chaining": "~7.14.2",
"@babel/plugin-syntax-class-properties": "~7.12.13",
"@babel/plugin-syntax-decorators": "~7.12.13",
"@babel/preset-typescript": "~7.13.0",

"babel-loader": "~8.2.2",

Instead, we should remove this code, and allow consumers of this plugin to use their own Webpack plugins for handling TypeScript.

Note that this would be a breaking change.

Hydration mismatch: incorrect number of rendered nodes.

Hi,

I am seeing the following error while running a sample LWC off-platform.

Error: [LWC error]: Hydration mismatch: incorrect number of rendered nodes. Client produced more nodes than the server.
import Sample from 'c/sample';

const availableFeature = detectFeatures();
const isCompatibleBrowser = Object.keys(availableFeature).some(
    feature => !availableFeature[feature]
);

if (isCompatibleBrowser) {
    unsupportedErrorMessage(availableFeature);
} else {
     customElements.define('c-omni', Sample.CustomElementConstructor);
}

I am using lwc-webpack-plugin 3.0.1

Empty / Sample LWC

import { LightningElement } from "lwc";

export default class Sample extends LightningElement {
    
}

Move LWC to peer dependency

Right now lwc-webpack-plugin relies on explicit versions of LWC:

"@lwc/babel-plugin-component": "~2.5.2",
"@lwc/compiler": "~2.5.2",
"@lwc/engine-dom": "~2.5.2",
"@lwc/module-resolver": "~2.5.2",
"@lwc/synthetic-shadow": "~2.5.2",
"@lwc/wire-service": "~2.5.2",

These should be moved to peerDependencies, because consumers of this plugin should be able to use whatever version of LWC they want, as long as it's compatible (2.x basically).

Note that this would be a breaking change.

Namespacing of modules

Hi

I have a setup where I use storybook to showcase components. In order for me to be able to push the components directly to a Salesforce org they need to be present in the "force-app/main/default/lwc" folder. That means when I run my local server, the components is not registered under the namespace "c" as they are when deployed to Salesforce.

Would it be possible to include an option to define a namspace for each module definition like showcased below?

"modules": [ { "dir": "src/demoComponents" }, { "namespace": "c" "dir": "force-app/main/default/lwc" } ]

Best
Rasmus

Local Directories are not supported as Modules

When loading lightning-base-components the entire config is working lovely, and I would like to work on my own modules which can be loaded to NPM.
The challenge is that I don't want to push them to NPM until they are working as expecting (this is in collaboration with another app).
The issue I am seeing is that when do
npm i my/local/path

it does not seem to support, and I get the following error from webpack when building from the main app and trying to pull in the components from the module bundle (sfmc-custom-sdk)

`ERROR in ../sfmc-custom-sdk/src/modules/common/notfound/notfound.html 1:0
Module parse failed: Unexpected token (1:0)
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

.....`

If I move the folder into node_modules then it does work again, but it means it is at risk of being overwritten easily, so I want to avoid this.

Is there any thought put into these scenarios or is this just going to be one of those limitations?

@import CSS stylesheets from node_modules aren't compiled

It seems that this plugin fails to import and compile CSS stylesheets imported within a component CSS itself like so:

@import 'file/from/node_modules.css';

This results in webpack erroring out with a syntax error since it doesn't know how to interpret the CSS file. If we follow Webpack's instructions to add a loader to handle this specific .css, the build error goes away but a browser error appears instead:

Uncaught TypeError: Failed to resolve module specifier "file/from/node_modules.css". Relative references must start with either "/", "./", or "../".

In Rollup, this just works whenever we use the @rollup/plugin-node-resolve plugin before the LWC plugin. Without that plugin the same issue occurs in Rollup.

It seems there should be 1 of 2 possible fixes:

  1. This webpack plugin needs to see CSS @import to files in node_modules and resolve it the same way it resolves CSS modules from node_modules, like @import 'lwc-namespace/css-module';
  2. The webpack config be updated to help this plugin know how to import that file on its own at build time. It does not seem to like having a separate loader try to handle that file for it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.