首页 \ 问答 \ 试图要求使用webpack的部分jquery(Trying to require parts of jquery with webpack)

试图要求使用webpack的部分jquery(Trying to require parts of jquery with webpack)

我正在使用这篇文章只导入我需要的jQuery的部分。

但是,我在使用这段代码时遇到了一个问题:

let $ = require('jquery/src/core');
require('jquery/src/core/init');
require('jquery/src/css');
console.log($);

我得到这个错误:

ERROR in ./~/jquery/src/selector-sizzle.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../external/sizzle/dist/sizzle in /home/vamsi/Do/highland-fun/bacon-form/node_modules/jquery/src
 @ ./~/jquery/src/selector-sizzle.js 1:0-14:3

这是我的webpack.config.js文件:

module.exports = {
    entry:'./app',
    output:{
      filename:'./bundle'
    },
    modules:{
      loaders:[
        {
           test:/jquery[\\\/]src[\\\/]selector\.js$/,
           loaders:['amd-define-factory-patcher-loader']
        }
      ]
    }
}

我试图用resolve.alias来解决这个问题:

resolve:{                                                                
  alias:{                                                                
   '../external/sizzle/dist/sizzle':'./node_modules/sizzle/dist/sizzle.js'
  }                                                                      
}

但它仍然会抛出与以前一样的错误。


I am using this article to import only the parts of jquery that I would need.

However, I am running into an issue when doing using this code:

let $ = require('jquery/src/core');
require('jquery/src/core/init');
require('jquery/src/css');
console.log($);

I get this error:

ERROR in ./~/jquery/src/selector-sizzle.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../external/sizzle/dist/sizzle in /home/vamsi/Do/highland-fun/bacon-form/node_modules/jquery/src
 @ ./~/jquery/src/selector-sizzle.js 1:0-14:3

This is my webpack.config.js file:

module.exports = {
    entry:'./app',
    output:{
      filename:'./bundle'
    },
    modules:{
      loaders:[
        {
           test:/jquery[\\\/]src[\\\/]selector\.js$/,
           loaders:['amd-define-factory-patcher-loader']
        }
      ]
    }
}

I have tried to use a resolve.alias to fix this:

resolve:{                                                                
  alias:{                                                                
   '../external/sizzle/dist/sizzle':'./node_modules/sizzle/dist/sizzle.js'
  }                                                                      
}

But it still throws the same error as before.


原文:https://stackoverflow.com/questions/35877475
更新时间:2022-11-11 19:11

最满意答案

最简洁的答案是不。 浏览器无法访问本地或服务器环境变量,因此dotenv无需查找。 相反,您可以在React应用程序中指定普通变量,通常在设置模块中。

可以使Webpack从构建机器获取环境变量并将它们烘焙到您的设置文件中。 但是,它实际上是在构建时替换字符串,而不是运行时。 因此,您的应用程序的每个版本将具有硬编码的值。 这些值可以通过process.env对象访问。

var nodeEnv = process.env.NODE_ENV;

此外,你可以使用DefinePlugin for webpack,它可以让你明确地指定不同的值,取决于你的构建目标(dev,prod等)。 请注意,您必须将JSON.stringify传递给它的所有值。

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),

这适用于任何类型的公共细节,但绝不能用于任何类型的私钥,密码或API机密 。 这是因为任何烘焙的值都是可公开访问的,并且如果它们包含敏感的细节可能会被恶意使用。 对于这些事情,您需要编写一些服务器端代码,并构建一个可以使用秘密对第三方API进行身份验证的简单API,然后将相关详细信息传递给客户端应用程序。 您的服务器端API充当中介,在保留您所需的数据的同时保护您的机密。


The short answer is no. A browser cannot access local or server environment variables so dotenv has nothing to look for. Instead, you specify ordinary variables in your React application, usually in a settings module.

Webpack can be made to take environment variables from the build machine and bake them into your settings files. However, it works be actually replacing strings at build-time, not run-time. So each build of your application will have the values hard-coded into it. These values would then be accessible through the process.env object.

var nodeEnv = process.env.NODE_ENV;

Additionally, you could use the DefinePlugin for webpack which lets you explicitly specify different values depending on your build target (dev, prod, etc.). Note that you have to JSON.stringify all values passed into it.

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),

This is fine for any sort of public details but should never be used for any sort of private keys, passwords or API secrets. This is because any values baked in are publicly accessible and could be used maliciously if they contain sensitive details. For those sorts of things, you need to write some server-side code and build a simple API which can authenticate with the 3rd party API using the secrets, then pass the relevant details along to your client-side application. Your server-side API acts as an intermediary, protecting your secrets while still getting the data you need.

相关问答

更多
  • 最简洁的答案是不。 浏览器无法访问本地或服务器环境变量,因此dotenv无需查找。 相反,您可以在React应用程序中指定普通变量,通常在设置模块中。 可以使Webpack从构建机器获取环境变量并将它们烘焙到您的设置文件中。 但是,它实际上是在构建时替换字符串,而不是运行时。 因此,您的应用程序的每个版本将具有硬编码的值。 这些值可以通过process.env对象访问。 var nodeEnv = process.env.NODE_ENV; 此外,你可以使用DefinePlugin for webpack ...
  • 最简单的答案是eval() ,但也是最不安全的: eval('Infinity') // Infinity 但在你的情况下, Number()可以正常工作: Number('Infinity') // Infinity 或者,包括支票: if(MAX_PAGES === 'Infinity') MAX_PAGES = Infinity; The easiest answer is eval(), but also the least safe: eval('Infinity') // Infinity ...
  • 创建任务以上传您的.env和database.yml .env示例如下: desc "Database config" task :setup_config, roles: :app do # upload you database.yml from config dir to shared dir on server put File.read("config/database.yml"), "#{shared_path}/config/database.yml" # make symli ...
  • 这是你如何让dotenv使用嵌套路径: require('dotenv').config({path:'relative/path/to/your/.env'}) 将它放在您想要的.env变量文件的顶部。 This is how you get dotenv working with nested paths: require('dotenv').config({path:'relative/path/to/your/.env'}) Place this at the top of the file y ...
  • 与dotenv文档中所述的dotenv ,您实际上需要使用.env文件中的export关键字来使参数可用于环境,例如 export FOO=foo 唯一的例外是,如果参数已经是一个环境变量。 例如,如果它已经在~/.zshrc导出,或者它已经是开始时获得的zsh环境的一部分(例如PATH或HOME )。 当更改到目录时,所有dotenv都会自动获取任何.env文件。 没有额外的“魔法”。 这意味着.env需要是一个有效的zsh脚本,并且其内容在当前shell会话的上下文中运行(基本上就像手动键入它一样)。 ...
  • 我想你也应该在你的Rakefile中需要dotenv require 'dotenv/tasks' load 'active_record/railties/databases.rake' 因此,在加载您的自定义任务时,dotenv将被加载并且ENV将填充数据。 I guess you should also require dotenv at your Rakefile require 'dotenv/tasks' load 'active_record/railties/databases.rake' ...
  • 当你调用find_dotenv而不是查找像 .env 这样的文件时, dotenv包会查找一个字面上称为.env的文件。 您可以通过将文件名传递给find_dotenv来使代码找到所需的文件,即 import dotenv found_dotenv = dotenv.find_dotenv('config.dotenv') print(found_dotenv) The dotenv package looks for a file that is literally called .env when ...
  • 如果我已正确理解您的问题,您想将一些数据传递到您正在渲染的EJS视图中吗? 如果是这样,那么这个问题可能会有用; 将变量传递给ExpressJS中的JavaScript 您必须在服务器上加载数据,然后将其传递到对象中,然后可以在视图中引用该对象。 If I've understood your question correctly you want to pass some data into the EJS view you're rendering? If so, then this question ...
  • 环境变量通常用于特定于环境的配置值,如数据库凭据,API端点等。 由于它们是特定于环境的,并且通常包含数据库凭据等敏感数据, .env不应提交.env文件。 如果要显示使用哪些环境变量,则一种方法是创建和提交样本文件: .env.sample DB_HOST=localhost DB_USERNAME= DB_PASSWORD= DB_DATABASE=our_project 然后由其他开发人员复制相同的内容并创建他们自己的.env文件(或者只是填充他们系统上的相关环境变量)。 Environment v ...
  • 不,Node.js不会自动读取.env文件。 对正在发生的事情的可能解释: 在运行程序之前,可能已在shell中设置了您正在使用的环境变量。 也许您的AWS凭证是由您的机器以其他方式存储/利用的。 (根据我们的评论对话,这看起来就像是你的情况,但是我还包括其他一些东西来帮助那些可能会看到相似内容的人。) 也许您正在加载的模块之一是读取.env文件。 @maxwell建议的其他信息: AWS CLI帮助页面指示配置值的优先级为: 命令行选项 环境变量 配置文件 所以听起来信息来自@maxwell的配置文件。 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)