简体   繁体   English

无法使用 webpack 和 Babel 为 Web 创建缩小的 JavaScript 库,而不需要输出 require()

[英]Can't Create Minified JavaScript Library for Web With webpack & Babel Without require() Being Output

I'd like to use the latest JavaScript constructs not supported by all browsers so I've turned to webpack and Babel.我想使用并非所有浏览器都支持的最新 JavaScript 结构,所以我转向了 webpack 和 Babel。

My code contains no requires but the output does.我的代码不包含任何要求,但输出包含。 This causes Uncaught ReferenceError: require is not defined when output is loaded in a browser.这会导致Uncaught ReferenceError: require is not defined在浏览器中加载输出时Uncaught ReferenceError: require is not defined

.babelrc

{
  "plugins": [
    "@babel/plugin-transform-runtime"
  ],
  "presets": [
    "@babel/preset-env"
  ]
}

webpack.config.js

const MinifyPlugin = require('babel-minify-webpack-plugin');

module.exports = {
  target: 'web',
  mode: 'production',
  entry: './uuuu.js',
  output: { filename: 'uuuu.min.js' },   
  plugins: [
    new MinifyPlugin(
      {},
      {
        minifyPreset: require('babel-preset-minify')
      }
    )
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
};

What to do?该怎么办?

I have had great experiences using the angular cli to build NPM JavaSscript libraries even if they are not Angular projects.即使它们不是 Angular 项目,我也有使用 angular cli 构建 NPM JavaScript 库的丰富经验。 You get the awesome build and test pipeline and can remove the Angular dependencies to create generic JavaScript libraries.您将获得出色的构建和测试管道,并且可以删除 Angular 依赖项以创建通用 JavaScript 库。

type类型

npm install -g @angular/cli

then然后

ng new my-lib --create-application=false

cd into the newly created folder and create a library cd 进入新创建的文件夹并创建一个库

ng generate library my-lib

Change into the folder projects/my-lib and remove the Angular dependencies from peerDependencies in the package.json folder and remove the demo Angular component, module and service.切换到文件夹 projects/my-lib 并从 package.json 文件夹中的 peerDependencies 中删除 Angular 依赖项,并删除演示 Angular 组件、模块和服务。

Now you have a world class TypeScript project ready to build and deploy to NPM.现在,您已准备好构建和部署到 NPM 的世界级 TypeScript 项目。

Type类型

ng build my-lib

then change into dist/my-lib and type然后更改为 dist/my-lib 并键入

npm publish

Why try and hand roll a build and test pipeline when you can have the experience of the Angular team behind you?当您拥有 Angular 团队的经验时,为什么要尝试手动构建和测试管道?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM