简体   繁体   English

webpack“外部”选项的意外字符“@”

[英]Unexpected character '@' for webpack "externals" option

I've found a lot of stuff about "Unexpected character '@'" happening with webpack, but none of it related specifically to, or helpful with, getting that error for the externals webpack option.我发现了很多关于 webpack 发生的“意外字符'@'”的内容,但没有一个与externals webpack 选项的错误特别相关或有帮助。 I've used this before, both with and without @-signs, without any trouble, so I don't know why webpack is getting cranky now.我以前用过这个,不管有没有@-signs,都没有任何麻烦,所以我不知道为什么webpack现在变得暴躁了。

const TerserPlugin = require('terser-webpack-plugin');

module.exports = () => {
  return {
    mode: 'production',
    target: 'node',
    entry: './build.ts',
    output: {
      path: __dirname,
      filename: `build.js`
    },
    node: {
      __dirname: false,
      __filename: false,
    },
    resolve: {
      extensions: ['.ts', '.js'],
      mainFields: ['es2015', 'module', 'main', 'browser']
    },
    module: {
      rules: [
        {
          test: /\.ts$/i,
          loader: 'ts-loader',
          options: { configFile: 'tsconfig-build.json' },
          exclude: [/\/node_modules\//]
        }
      ]
    },
    externals: ['chalk', '@tubular/util'],
    optimization: {
      minimize: true,
      minimizer: [new TerserPlugin({
        terserOptions: {
          mangle: false,
          output: { max_line_len: 511 }
        }
      })],
    },
  };
};

The @ is a necessary part of the package name that I want to exclude, and I've exclude such packages before, so this is both mysterious and annoying. @ 是我想排除的 package 名称的必要部分,我之前已经排除了此类包,所以这既神秘又烦人。

Anyone have any idea what's wrong here?有人知道这里有什么问题吗?

I found an answer, but it's certainly not the answer I was looking for.我找到答案,但这肯定不是我想要答案。

If I use the package webpack-node-externals , I can externalize all node_modules like this:如果我使用 package webpack-node-externals ,我可以像这样外部化所有node_modules

const nodeExternals = require('webpack-node-externals');

 // ...

    externalsPresets: { node: true },
    externals: [nodeExternals()],

In this particular case excluding all node externals happens to be just fine, so webpack-node-externals solves my immediate problem.在这种特殊情况下,排除所有节点外部恰好很好,所以webpack-node-externals解决了我的直接问题。 But if I wanted to be more selective, and wanted to exclude a package with an @ in the name, I'd still have a mystery on my hands.但是,如果我想更有选择性,并且想排除名称中带有 @ 的 package,我的手上仍然是个谜。

I found a solution, I was also facing the same issue with Vue.js Project --mode production .我找到了一个解决方案,我也面临与 Vue.js Project --mode --mode production相同的问题。 All other modes were working fine.所有其他模式工作正常。

externals:[
      {
        ["@company/library-name"]:{
          root: "@company/library-name"
        }
      }
    ]

This is basically using the object syntax from official docs .这基本上是使用官方文档中的 object 语法。

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

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