js: Let ESBuild handle all imports from node_modules

This commit fixes some issues where modules in /assets share the same name as in node_modules.

This was not intended, and with this commit the node_modules-components should be isolated. If you want to redefine something inside node_modules, use the `defines` option.

Fixes #7948
This commit is contained in:
Bjørn Erik Pedersen
2020-11-13 08:54:29 +01:00
committed by GitHub
parent 5e03f644a4
commit 78f227b664
6 changed files with 26 additions and 46 deletions

View File

@@ -19,7 +19,6 @@ import (
"io/ioutil"
"path/filepath"
"strings"
"sync"
"github.com/pkg/errors"
@@ -113,11 +112,6 @@ func decodeOptions(m map[string]interface{}) (Options, error) {
return opts, nil
}
type importCache struct {
sync.RWMutex
m map[string]api.OnResolveResult
}
var extensionToLoaderMap = map[string]api.Loader{
".js": api.LoaderJS,
".mjs": api.LoaderJS,
@@ -141,16 +135,18 @@ func loaderFromFilename(filename string) api.Loader {
func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) {
fs := c.rs.Assets
cache := importCache{
m: make(map[string]api.OnResolveResult),
}
resolveImport := func(args api.OnResolveArgs) (api.OnResolveResult, error) {
isStdin := args.Importer == stdinImporter
var relDir string
if !isStdin {
relDir = filepath.Dir(fs.MakePathRelative(args.Importer))
rel, found := fs.MakePathRelative(args.Importer)
if !found {
// Not in any of the /assets folders.
// This is an import from a node_modules, let
// ESBuild resolve this.
return api.OnResolveResult{}, nil
}
relDir = filepath.Dir(rel)
} else {
relDir = filepath.Dir(opts.sourcefile)
}
@@ -204,8 +200,7 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) {
return api.OnResolveResult{Path: m.Filename(), Namespace: nsImportHugo}, nil
}
// Not found in /assets. Probably in node_modules. ESBuild will handle that
// rather complex logic.
// Fall back to ESBuild's resolve.
return api.OnResolveResult{}, nil
}
@@ -214,26 +209,7 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) {
Setup: func(build api.PluginBuild) {
build.OnResolve(api.OnResolveOptions{Filter: `.*`},
func(args api.OnResolveArgs) (api.OnResolveResult, error) {
// Try cache first.
cache.RLock()
v, found := cache.m[args.Path]
cache.RUnlock()
if found {
return v, nil
}
imp, err := resolveImport(args)
if err != nil {
return imp, err
}
cache.Lock()
defer cache.Unlock()
cache.m[args.Path] = imp
return imp, nil
return resolveImport(args)
})
build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: nsImportHugo},